我多次遇到一个问题,如何将单词读到行尾?
例如:
2
hello this is a word
hi five
so i want to output
case 1:
hello
this
is
word
case 2:
hi
five
问问题
1786 次
3 回答
1
您可以循环遍历字符串中的每个字符以及遇到\n
or\r
字符时。可能是这样的?:
char str[] = "Hello this is a word\nhi five";
int i;
for(i = 0; str[i] != '\0'; i++)
{
if(str[i] != '\n' && str[i] != '\r') //do something with str[i]
else //do something if a new line char is found
}
这样,您可以准确地选择在换行时要执行的操作。我在解析文件时经常使用这种方法,我将每一行写入缓冲区,处理缓冲区,然后开始将下一行移入缓冲区进行处理。
于 2012-08-25T18:18:27.757 回答
-1
其中一项危险功能将为您提供名为gets
.
否则:-
char line[512];
int count=0;
char input=1;
while((input=getchar())!='\n')
line[count++]=input;
于 2012-08-25T18:11:55.363 回答
-1
#include <stdio.h>
int main(){
int i, dataSize=0;
scanf("%d%*[\n]", &dataSize);
for(i = 1; i<=dataSize;++i){
char word[64];
char *p=word, ch=0;
printf("case %d:\n", i);
while(EOF!=ch && '\n'!=ch){
switch(ch=getchar()){
case ' '://need multi space char skip ?
case '\t':
case '\n':
case EOF:
*p = '\0';
printf("%s\n", p=word);
break;
default:
*p++ = ch;
}
}
if(ch == EOF)break;
}
return 0;
}
或者
#include <stdio.h>
#include <ctype.h>
int main(){
int i, dataSize=0;
scanf("%d%*[\n]", &dataSize);
for(i = 1; i<=dataSize;++i){
char word[64],ch = 0;
int stat = !EOF;
printf("case %d:\n", i);
while(EOF!=stat && '\n'!=ch){
ch = 0;
stat=scanf(" %s%c", word, &ch);
if(EOF!=stat || isspace(ch)){
printf("%s\n", word);
}
}
if(EOF==stat)break;
}
return 0;
}
于 2012-08-26T09:15:15.290 回答