如何找出c中是否有换行符或数字?
我有一个作业,我必须读到“?”字符,然后检查它后面是数字和换行符,还是换行符,然后是数字,然后是换行符。 我检查了“?”之后的第一个字符 如果(scanf(“%c”,c)='\n') 但这只适用于第一个是换行符的情况,而当它不是换行符时,我想读取数字,它会剪切第一个数字。。。例如,它的读数不是133,而是33 ... 我该怎么做 我也试着把炭放回去,但那不起作用 请帮助:)使用,或者更好的是,(like)读取整行,然后使用或(like)解析该行 不要忘记仔细阅读您正在使用的每个函数的文档。处理错误情况-可能使用如何找出c中是否有换行符或数字?,c,char,newline,C,Char,Newline,我有一个作业,我必须读到“?”字符,然后检查它后面是数字和换行符,还是换行符,然后是数字,然后是换行符。 我检查了“?”之后的第一个字符 如果(scanf(“%c”,c)='\n') 但这只适用于第一个是换行符的情况,而当它不是换行符时,我想读取数字,它会剪切第一个数字。。。例如,它的读数不是133,而是33 ... 我该怎么做 我也试着把炭放回去,但那不起作用 请帮助:)使用,或者更好的是,(like)读取整行,然后使用或(like)解析该行 不要忘记仔细阅读您正在使用的每个函数的文档。处理错
peror
然后exit
来显示有意义的消息。请注意,scanf
和sscanf
返回扫描项目的数量,并了解%n
,并且strtol
可以设置一些结束指针
请记住,在某些操作系统(例如Linux)上,终端是一个线程,通常由内核进行缓存;所以在你按下返回键之前,没有任何东西被发送到你的程序(你可以在一个终端上做原始输入,但是它是OS特有的;在Linux上也考虑代码< > RealLoad < /代码>)。 < > <代码> GETLINE < /代码>的一个优点,在<<代码> FGES(或者一个遥远的<代码> SCANF)即
getline
返回成功读取的实际字符数。这允许使用return togetline
在末尾简单检查换行符。例如:
while (printf ((nchr = getline (&line, &n, stdin)) != -1)
{
if (line[nchr - 1] = '\n') /* check whether the last character is newline */
line[--nchr] = 0; /* replace the newline with null-termination */
/* while decrementing nchr to new length */
#包括
内部主(空){
int-num;
scanf(“%*[^?]?”;//一直读到“?”
而(1==scanf(“%d”、&num)){
printf(“%d\n”,num);
}
返回0;
}
您可能希望从开始。并阅读有关例如安的内容。提示:nchr--
应该是--nchr
。
this line: if (scanf("%c",c)=='\n') ...; will NEVER work.
scanf returns a value that indicates the number of successful parameter conversions.
suggest:
// note: 'c' must be defined as int, not char
// for several reasons including:
// 1) getchar returns an int
// 2) on some OSs (dos/windows) '\n' is 2 characters long
// 3) if checking for EOF, EOF is defined as an int
if( '\n' == (c = getchar() ) )
{ // then found newline
...
#include <stdio.h>
int main (void){
int num;
scanf("%*[^?]?");//read till the "?"
while(1==scanf("%d", &num)){
printf("%d\n", num);
}
return 0;
}