当我调用此功能时,程序停止
int text_input(char pinax[N][M])
{
char endword[10 +1] = "T*E*L*O*S*";
int i=0;
int y=0;
char word[11];
while (fgets(word,11,stdin), strcmp(word,endword)) {
if(strcmp(word,'\0')!=0){
strcpy(pinax[i++],word);
y++;
}
}
return y;
}
因此,我尝试将用户输入字符串作为输入,然后将其存储在2D数组PINAX [n] [m]中,其中n = m = 11,由于某种原因,它在运行时结束。当我使用scanf代替fget时,没有问题,但是我更喜欢fgets,以便我可以在字符串内有空格。除此之外,当我打印pinax [0](数组的第一个字符串)时,在fgets方法的情况下,它没有打印什么,我怀疑这是无效的元素,当我打印pinax [1]时,这是第二个它的数组的字符串打印了用户输入的第一个单词。急需任何帮助。
int text_input(char pinax[N][M])
{
char endword[10 +1] = "T*E*L*O*S*";
int i=0;
int y=0;
char word[11];
while (fgets(word,11,stdin), strcmp(word,endword)) {
if(strcmp(word,'\0')!=0){
strcpy(pinax[i++],word);
y++;
}
}
return y;
}
So I try to take as input a string from user and store it in a 2d array pinax[N][M], where N = M = 11 and for some reason it ends when I run it. When I use scanf instead of fgets there is no problem but I prefer fgets so that I can have spaces inside the string. In addition to that, when I print pinax[0](first string of the array) in the case of the fgets method,it prints nothing, which I suspect is the NULL element and when I print pinax[1] which is the second string of the array it prints the first word that the user typed in. Any help is much needed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
strcmp
的呼叫调用不确定的行为。该函数期望两个指针,但呼叫中的第二个参数是转换为空指针的字符。
至于您对空的第一个字符串的问题,这是输入缓冲区中存在的新行字符
'\ n'
的结果。为了避免问题,您可以使用函数
scanf
。例如,请注意格式字符串中的领先空间。它允许跳过白空间字符。
This call of
strcmp
invokes undefined behavior. The function expects two pointers but the second argument in the call is a character that is converted to a null pointer.
As for your problem with the empty first string then it is the result of the presence in the input buffer the new line character
'\n'
of a preceding input.To avoid the problem you can use the function
scanf
. For examplePay attention to the leading space in the format string. It allows to skip white space characters.