如何输入2个用换行符分隔的字符串?
我的问题:
首先,我需要给出需要获取的字符串数量,然后再获取并显示这些字符串。
我尝试过:
代码:
#include <stdio.h>
#include <string.h>
int main()
{
int n,i = 0;
scanf("%d", &n);
char arr[n][100];
for(int i = 0; i < n; i++)
{
scanf("%[^\n]s", arr[i]);
}
for(int i = 0; i < n; i++)
{
printf("%s\n", arr[i]);
}
return 0;
}
我的输入是:
2 I am
Aravind
我的输出是:
I am
þ
第一行我得到了正确的提示,但是第二行显示了一些垃圾值。帮我解决这个问题。
答案 0 :(得分:7)
答案 1 :(得分:1)
您已经有建议不要使用scanf
。但是,如果“必须”使用int main()
{
int n,i = 0;
scanf("%d", &n);
scanf("%*[\n]");
/*this will read the \n in stdin and not store it anywhere. So the next call to
* scanf will not be interfered with */
char **inputs;
inputs = malloc(n * sizeof(char *));
for (i = 0; i < n; i++)
{
inputs[i] = malloc(100 * sizeof(char));
}
for(i = 0; i < n; i++)
{
scanf("%*[\n]");
scanf("%100[^\n]", inputs[i]);
}
for(i = 0; i < n; i++)
{
printf("%s\n", inputs[i]);
}
return 0;
}
,则可以考虑以下方法:
这是更新的代码。
console.log(require.resolve('.') === __dirname); // true
答案 2 :(得分:-2)
使用gets(arr [i])代替scanf。