所以我一直在尝试读取输入字符串,然后不使用scanf()
和printf()
,而是使用getchar()
和putchar()
来打印输入字符串。
好像程序卡在循环中,我无法发现错误。
#include <stdio.h>
void getstring(char *c)
{
char inS[100];
char n;
int i = 0;
while ((n = getchar()) != '\n') {
inS[i] = n;
i++;
}
inS[i] = '\0';
i = 0;
while (inS[i] != '\0') {
putchar(inS[i]);
i++;
}
}
main()
{
char *prompt;
prompt = "Enter a sentence: \n";
getstring(&prompt);
printf("%s", prompt);
}
答案 0 :(得分:1)
也许你没有在你的stdin中添加\ n?执行代码是成功的。你也没有修改传递char *c
,为什么?要修改指针,您应该将指针传递给指针(How do I modify a pointer that has been passed into a function in C?)
答案 1 :(得分:1)
您的代码存在一些问题。这是更正后的代码:
#include <stdio.h>
void getstring(void) /* You don't use the passed argument. So, I've removed it */
{
char inS[100];
/* `char n;` getchar() returns an int, not a char */
int n;
int i = 0;
while (i < 99 && (n = getchar()) != '\n' && n != EOF) /* Added condition for preventing a buffer overrun and also for EOF */
{
inS[i] = n;
i++;
}
inS[i] = '\0';
putchar('\n'); /* For seperating input and output in the console */
i = 0;
while (inS[i] != '\0')
{
putchar(inS[i]);
i++;
}
putchar('\n'); /* For cleanliness and flushing of stdout */
}
int main(void) /* Standard signature of main */
{
char *prompt;
prompt = "Enter a sentence: \n";
printf("%s", prompt); /* Interchanged these two lines */
getstring(); /* Nothing to pass to the function */
return 0; /* End main with a return code of 0 */
}
注意:输入的循环将在
时结束\n
( Enter )。EOF
。stdin
读取了99个字符。答案 2 :(得分:0)
首先,您可以将数组的所有元素设置为NULL。
char inS[100] = {"\0",};
您可以使用gets()从控制台获取字符串。有些事情如下。
你的代码
while ((n = getchar()) != '\n') {
inS[i] = n;
i++;
}
将其修改为:
gets(inS);
然后你可以按照自己的意愿进行其他操作。
答案 3 :(得分:0)
getchar就会用\ 0替换\ n字符。所以n永远不会是\ n。 你应该试试getc或fgetc。
答案 4 :(得分:0)
您没有打印新行。在putchar(ch)
之后,您应该使用putchar('\n')
来打印新行
答案 5 :(得分:0)
#include <stdio.h>
void getstring(char *c)
{
char n;
int i = 0;
while ((n = getchar()) != '\n')
{
*c=n;
c++;
}
c = '\0';
main()
{
char inS[100];
char *prompt=inS;
getstring(prompt);
printf("%s", prompt);
}
强文
在main()函数中,只声明了指针,但它没有被赋值给任何符号,换句话说是指定的指针,但它没有引用任何内存位置。在这个解决方案中解决了这个问题