我试图编写一个程序,该程序需要从用户(控制台)开始一行,直到遇到逗号,句号或换行符,并告诉按照特定模式读取了多少个字符。
正确读取字符串,但计数不正确。
#include <stdio.h>
int main()
{
int n;
char s[100];
// The following line should read a string until (. or , or new-line in encountered)
// and %n should tell me the no of characters it read until that point
scanf("%[^.,\n]s%n", s, &n);
// The String in okay
printf("%s\n", s);
// But count of characters read is 0
printf("%d\n",n);
return 0;
}
5个问题:
在"s"
中"%[^.,\n]s%n"
,因为可以不停止扫描's'
后读取%[^.,\n]
。%[^.,\n]
会全部阅读's'
。因此,后面的代码"%n"
永远不会发生n
,而后来打印的0
代码则是错误的代码-打印未初始化的代码-n
可能是任意代码int
或陷阱。
扫描没有宽度限制。第99个字符之后发生坏事。
使用时scanf("%[^.,\n]s%n", s, &n);
,s
如果第一个字符是,扫描将不会保存任何内容.,\n
。后来的列印s
不良,因为s[]
尚未初始化。
代码无法检查的返回值scanf()
。
scanf()
不一定会按照“编写从用户那里获取代码的程序”的指示来读取代码行-停止使用scanf()
。
C Std Lib定义了以下一行,因此代码应尝试读取整行。
文本流是由行组成的有序字符序列,每行由零个或多个字符加上一个终止换行符组成。
scanf()
另类
int n = 0;
char s[100];
s[0] = '\0';
int cnt == scanf("%99[^.,\n]%n", s, &n);
if (cnt == EOF) puts("Nothing was read");
else printf("%s\n", s);
更好的选择
我建议您使用fgets()
而不是scanf()
:从user中提取一行。
char s[100];
if (fgets(s, sizeof s, stdin)) {
size_t n = strcspn(s, ".,\n"); // offset of string that does not have .,\n
s[n] = '\0';
printf("%s\n", s);
printf("%zu\n", n);
}
注意:超过约100行的行需要附加代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句