gpt4 book ai didi

c - 为什么这只读取 n-1 个字符串?

转载 作者:太空宇宙 更新时间:2023-11-04 06:25:31 27 4
gpt4 key购买 nike

我正在尝试编写一个从 stdin 读取并写入 stdout 的程序不同长度的字符串数组,但我的程序只读取 n-1 字符串,尽管我特别告诉它读取 n。到目前为止,这是我得出的结论:

int main()
{
char **vectorschar;
int n, i;
char c;

printf("How many strings will you read? : ");
scanf("%d", &n);

vectorschar = (char**)calloc(n, sizeof(char*));

for(i = 0; i < n; i++)
{
vectorschar[i] = (char*)calloc(30, sizeof(char));
}

for(i = 0; i < n; i++)
{
gets(vectorschar[i]);
}

for(i = 0; i < n; i++)
{
puts(vectorschar[i]);
}
return 0;
}

你能给我指明正确的方向吗?我仍在学习字符串、IO 和内存在 C 中的工作方式,如果这个问题愚蠢而明显,我深表歉意。

最佳答案

行后

scanf("%d",&n);

被执行后,换行符 '\n' 留在流中。它在第一次调用 gets() 时使用。

您可以使用以下方法跳过换行符:

scanf("%d%*[^\n]",&n);
getchar();

关于c - 为什么这只读取 n-1 个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27449835/

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