gpt4 book ai didi

C程序读取和存储字符串

转载 作者:太空宇宙 更新时间:2023-11-04 07:09:36 24 4
gpt4 key购买 nike

我正在用 C 编写一段代码,它迭代 T 次,每次将一首小歌曲​​的文本作为输入,它将对其执行一些计数操作(计算每个单词的长度)。现在我只是在测试输入是否有效,但它没有。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_SONG_SIZE 501

int main(void){
int T;
scanf("%d", &T);
while(T--){
char* song = malloc(MAX_SONG_SIZE);
if(song == NULL){
printf("malloc failed");
return 1;
}
fgets(song, MAX_SONG_SIZE, stdin);
printf("foo\n");
free(song);
}
return 0;
}

我正在使用 fgets() 因为单词之间的空格和动态内存分配因为我不能只为所有歌曲使用一个数组,上一次迭代的字符将保留在数组中。

但是有一个问题。它在第一次迭代中跳过了 fgets(),只写了“foo”,没有等我插入一个字符串。

这是一个如何使用初始输入“3”进行打印的示例:
3

这是一个测试

另一个测试


用替代printf("foo\n");printf("<<%s>>\n", song);输出是这样的:

3<br>
<< <br>
>> <br>
test <br>
<<test <br>
>> <br>
another test <br>
<<another test <br>
>> <br>

我该如何解决这个问题?如果您有任何建议,欢迎您。

最佳答案

输入缓冲区中有一个\n,参见http://c-faq.com/stdio/scanfinterlace.html

引用自链接:

As a general rule, you shouldn't try to interlace calls to scanf with calls to gets() (or any other input routines); scanf's peculiar treatment of newlines almost always leads to trouble. Either use scanf to read everything or nothing.

关于C程序读取和存储字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29452976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com