可能重复:
Any cool function to replace readln from pascal in ansi c?文字阅读,直到行结束
我曾经遇到过一个问题几倍如何读字行的结尾?
例如:
2
hello this is a word
hi five
so i want to output
case 1:
hello
this
is
word
case 2:
hi
five
可能重复:
Any cool function to replace readln from pascal in ansi c?文字阅读,直到行结束
我曾经遇到过一个问题几倍如何读字行的结尾?
例如:
2
hello this is a word
hi five
so i want to output
case 1:
hello
this
is
word
case 2:
hi
five
一个危险的功能将为您提供被命名为gets
解决方案。
否则: -
char line[512];
int count=0;
char input=1;
while((input=getchar())!='\n')
line[count++]=input;
你可以通过字符串中的每个字符循环,当你遇到一个\n
或\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
}
通过这种方式,你可以选择满足正是你想要在一个新的生产线的情况下做什么。在解析文件时,我倾向于使用这种方法,我将每行写入缓冲区,处理缓冲区,然后开始将下一行移动到缓冲区中进行处理。
#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;
}