简体   繁体   English

我无法使该程序正常工作。

[英]i cant get this program to work correctly.

I have been asked to modify a program to read characters rather than numbers. 我被要求修改程序以读取字符而不是数字。 i modified the array into a char array. 我将数组修改为char数组。 changed the two "%d" to "%c" as below 如下将两个“%d”更改为“%c”

void main (void) { void main(void){

char a[100];
int counter;
int b;

counter = 0;

printf("please enter the length of the array:   ");
scanf("%d", &b );

while (counter != b)
{
    printf("please enter character:     ");
    scanf("%c", &a[counter]);
    counter++;
}

    a[counter] = '\0' ;
    counter = 0;

    while (a[counter] != '\0')
 {
printf("\n");
printf("%c",a[counter]);
counter++;
 }

 }

when i run this the program does this: 当我运行此程序时,将执行以下操作:

please enter the length of the array: (4) 请输入数组的长度:(4)
please enter character: please enter character: (a) 请输入字符:请输入字符:(a)
please enter character: please enter character: (a) 请输入字符:请输入字符:(a)

a 一种

a 一种


() are used to indicate the user inputs. ()用于指示用户输入。

would be really good if i could get some help. 如果我能得到一些帮助,那将是非常好的。

You have to remember that scanf leaves the newline in the input buffer, so when you try to read a character it will that newline. 您必须记住, scanf将换行符留在输入缓冲区中,因此当您尝试读取字符时,它将换行。

The solution is very simple: Tell scanf to read and discard leading whitespace, by adding a space in the format code: 解决方案非常简单:通过在格式代码中添加空格,告诉scanf读取和丢弃前导空白:

scanf(" %c", &a[counter]);
/*     ^           */
/*     |           */
/* Note space here */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有人可以请问为什么这个程序不能正常运行。 我是C新手 - Could someone please why this program is not running correctly. I'm new to C 程序在没有声明 wait() 函数后编译并正常工作。 为什么? - Program compiles after no declaration for wait() function and works correctly. Why? 我的快速排序无法正常工作。 我做错了什么? - My quickSort is not working correctly. What did I do wrong? 无法将C程序与strsep()和getenv()一起使用 - Cant get C program and strsep() and getenv() to all work together 我的程序运行正常,但收到警告 - My program is working correctly, but I get a warning 从文件读取输入时,我的C程序无法正确读取整数。 有什么建议么? - When reading input from a file, my C program is not reading the integers correctly. Any suggestions? 回文程序中的这个指针是什么我无法得到正确的结果 - whats this pointer in palindrome program i cant get correct result 我不认为我正确使用指针。 C - I don't think I'm using pointers correctly. C 如何让计数器在这个 C 程序中工作? - How to I get the counter to work in this C program? 我在C中实现链接列表,我的addhead功能无法正常工作。 怎么了? - I am implementing linked lists in C, and my addhead function is not working correctly. What's wrong?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM