'\n' 在 memset 之后保存在数组中 (C)
'\n' saved in array after memset (C)
我读取字符直到 '\n',将它们转换为 int 并对数字求和,直到结果只有一位。
我无法使用 mod 或 .
第一个运行很顺利,但是第二个保持运行ning而不是等待\n。
有什么理由保留'\n'?
#include<stdio.h>
int main(){
char str[8], conv_str[8],c;
int i,val,ans = 0;
while(1){
printf("Enter 8 values(0-9) :\n");
scanf("%[^\n]", str); // Scan values to str untill \n
for(i = 0;i < 8;i++){
val = str[i]-48; //convert from asci to int
ans += val;
}
while(ans > 9){
// itoa convert int to string, str(the input) is the buffer and 10 is the base
itoa(ans,conv_str,10);
ans = (conv_str[0]-48) + (conv_str[1]-48) ;
}
printf("the digit is: %d", ans);
printf("\ncontinue? (y/n)\n");
scanf("%s", &c);
if (c == 'n')
break;
memset(str, 0, sizeof(str));
}
return 0;
}
TIA
您的代码存在多个问题。其中一些是
scanf("%s", &c);
是错误的。 c
是 char
,您必须为此使用 %c
转换说明符。
您从未检查过 return value of scanf()
调用以确保成功。
扫描字符输入时,您没有清除任何现有输入的缓冲区。缓冲区中已经存在的任何现有字符,包括换行符 ('\n'
) 都将被视为 %c
的有效输入。您需要在读取字符输入之前清除缓冲区。
我读取字符直到 '\n',将它们转换为 int 并对数字求和,直到结果只有一位。
我无法使用 mod 或 .
第一个运行很顺利,但是第二个保持运行ning而不是等待\n。
有什么理由保留'\n'?
#include<stdio.h>
int main(){
char str[8], conv_str[8],c;
int i,val,ans = 0;
while(1){
printf("Enter 8 values(0-9) :\n");
scanf("%[^\n]", str); // Scan values to str untill \n
for(i = 0;i < 8;i++){
val = str[i]-48; //convert from asci to int
ans += val;
}
while(ans > 9){
// itoa convert int to string, str(the input) is the buffer and 10 is the base
itoa(ans,conv_str,10);
ans = (conv_str[0]-48) + (conv_str[1]-48) ;
}
printf("the digit is: %d", ans);
printf("\ncontinue? (y/n)\n");
scanf("%s", &c);
if (c == 'n')
break;
memset(str, 0, sizeof(str));
}
return 0;
}
TIA
您的代码存在多个问题。其中一些是
scanf("%s", &c);
是错误的。c
是char
,您必须为此使用%c
转换说明符。您从未检查过 return value of
scanf()
调用以确保成功。扫描字符输入时,您没有清除任何现有输入的缓冲区。缓冲区中已经存在的任何现有字符,包括换行符 (
'\n'
) 都将被视为%c
的有效输入。您需要在读取字符输入之前清除缓冲区。