如何从用户输入的C中读取字符串,放入数组并打印 [英] How to read a string from user input in C, put in array and print
问题描述
我对C语言还很陌生,我读过一本C书的几章,现在我必须做作业,但我都很困惑,希望有人能帮助我。
我必须从用户(字符数组)输入中读取2个字符串,最大长度为100个字符,并将其转换为大写字母,并在每个单词之后用换行符\n打印出来。 / p>
直到现在我有了:
int main(){
char chars [100];
int i = 0;
char str1;
char str2;
int j = 0;
scanf( \n%c,str1);
scanf( \n%c,str2);
而(str1 [i]!=‘0){
字符[i] = str1 [i];
toupper(chars [i]);
printf(chars [i]);
i ++;
}
而(str2 [j]!=‘\0'){
chars [j] = str2 [j];
toupper(chars [j]);
printf(chars [j]);
j ++;
}
返回0;
}
在接受用户的2个输入后,它说停止运行并说运行失败。
这是您的直接问题:
scanf( \n%c,str1);
此格式字符串告诉 scanf
读取一些内容空格后跟一个字符的数量,该字符将存储在 str1
中。
@ H2CO3是正确的: scanf
几乎永远不是从用户读取输入的正确答案。它不执行边界检查,并且对用户输入的格式过于挑剔。一个意想不到的角色会完全混淆它。强烈建议您使用 fgets
代替:
fgets(str1,100,stdin);
如果不允许这样做,您应该问教授为什么不这样做。认真。
如果您绝对必须使用 scanf
来读取此处的输入,则可以按照@ user2479209描述的方式进行操作
您的程序还有另一个问题,就是 toupper(chars [i])
不会更改存储在 chars [i]
中的值。您必须将 toupper
的结果显式分配回数组,例如:
chars [i] = toupper(chars [i]);
I'm fairly new to C and I've read a few chapters of a C book I have and now I have to make an assignment but I am all confused hope someone can help me out.
I have to read 2 strings from user (char arrays) input with a max length of 100 characters and convert them to capital letters and print them out with a newline \n after each word.
Until now I have this:
int main() {
char chars[100];
int i = 0;
char str1;
char str2;
int j = 0;
scanf("\n %c", str1);
scanf("\n %c", str2);
while (str1[i] != '\0') {
chars[i] = str1[i];
toupper(chars[i]);
printf(chars[i]);
i++;
}
while (str2[j] != '\0') {
chars[j] = str2[j];
toupper(chars[j]);
printf(chars[j]);
j++;
}
return 0;
}
after it takes the 2 inputs from user, it says stops running and says run failed.
This is your immediate problem:
scanf("\n %c", str1);
This format string tells scanf
to read some amount of whitespace followed by a single character, which is to be stored in str1
.
@H2CO3 is right: scanf
is almost never the right answer for reading input from the user. It performs no bounds checking and is too finicky about the format of user input; one unexpected character will completely confuse it. You are very strongly encouraged to use fgets
instead if at all possible:
fgets(str1, 100, stdin);
If you are not allowed to do this, you should ask your professor why not. Seriously.
If you absolutely must use scanf
to read input here, you can do it the way @user2479209 described in their answer.
There is another problem with your program, which is that toupper(chars[i])
will not change the value stored in chars[i]
. You have to assign the result of toupper
back to the array explicitly, e.g.:
chars[i] = toupper(chars[i]);
这篇关于如何从用户输入的C中读取字符串,放入数组并打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!