使用 scanf() 函数 [英] Using the scanf() function
问题描述
我打算修改一个特定字符串的每个其他字母.但就本程序而言,这些都不会发生.到目前为止,我已经从用户那里获取了一个字符串并将其存储在 userinput
中并打算打印它.
I intend to modify each other letter of a particular string. But for the purposes of this program none of that occurs. So far I've grabbed a string from the user and stored it in userinput
and intend to print it.
#include <stdio.h>
#include <string.h>
int main(void) {
char userinput[256] ="";
printf("Enter somthing to change:\n");
scanf("%s", &userinput);
printf("%s\n", userinput);
int k = 2; // This is just here to do something every time k is even
int j = strlen(userinput);
for (int i = 0; i < j; i++) {
if(k % 2 == 0) {
printf("%s", userinput[i]);
k++;
}
else {
printf("%s", userinput[i]);
k++;
}
}
}
strlen()
函数在 userinput
上不起作用.我认为这是因为 strlen()
应该取字符串的第一个字符的地址,然后迭代直到到达一个空字符,但 scanf 实际上并没有创建一个空字符.在不知道字符串长度的情况下,我想不出在字符串后面添加 '\0'
的方法.
The strlen()
function however does not work on the userinput
. I figure this is because strlen()
is supposed to take the address of the first char of a string and then iterate until reaching a null char but scanf doesn't actually create a null char.
I couldn't figure out a way of adding the '\0'
after the string without first knowing the length of the string.
如果存储在数组中,我将如何访问存储字符序列的长度?
How would I go about accessing the length of a stored character sequence if it's stored in an array?
推荐答案
这个:
scanf("%s", &userinput);
应该是:
scanf("%s", userinput);
操作员 &
的地址是不需要的,并且不正确.当传递给函数时,数组衰减到它们的第一个元素的地址.scanf("%s")
将附加一个空终止字符,因此没有必要显式插入一个.
The address of operator &
is unrequired, and incorrect. Arrays decay to the address of their first element when passed to a function. scanf("%s")
will append a null terminating character so it is unnecessary to explicitly insert one.
为了防止潜在的缓冲区溢出,指定scanf()
应该写入userinput
的最大字符数.这应该比 userinput
的大小小 1,为终止空字符留出空间:
To prevent potential buffer overrun specify the maximum number of characters that scanf()
should write to userinput
. This should be one less than the size of userinput
, leaving room for the terminating null character:
scanf("%255s", userinput);
不正确的格式说明符(这是未定义的行为)被用于打印 userinput
的 char
acters: use %c
not <代码>%s.这:
The incorrect format specifier (which is undefined behaviour) is being used to print the char
acters of userinput
: use %c
not %s
. This:
printf("%s", userinput[i]);
必须是:
printf("%c", userinput[i]);
这篇关于使用 scanf() 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!