C: scanf chars into array

2019-10-10 07:12发布

just starting C and want to know how to enter an unknown numbers of char into array, when the finishing symbol will be '~'

#include <stdio.h>
#define N (499)

int main()
{
    int count;
    int i;
    char input;
    char text[N];


    printf("Text:\n");
    scanf("%c", &input);

    while (input != '~')
    {
        for(i = 0; i < N; i++)
        {
            text[i] = input;
            scanf("%c", &input);
            count++;
        }
    }

return 0;
}

But i keep getting an infinite loop

thanks!

标签: c arrays char
3条回答
成全新的幸福
2楼-- · 2019-10-10 08:10

Remove the while loop and replace the for loop with:

 for(i = 0; i < N && input != '~'; i++)

Also it is a good idea to finish your string with a terminating null character so the program knows where the string ends. So after the for loop add:

 text[i] = '\0';

Alternatively you can use some scanf regex to avoid loops alltogether. For example:

        scanf("%498[^~]", text);

will read 498 characters in the array text until the ~sign is met. It will also put the terminating character to the string.

(you should not usually use scanf, but it is good enough for a beginner)

Edit: thanks to some random guy, "amis" or smth(please tell your name) a mistake replaced.

查看更多
姐就是有狂的资本
3楼-- · 2019-10-10 08:13

If you are using count for counting initialize it to zero first.

int count = 0;

You are using for loop inside a while loop, for every character input the for loop will run N times. so check input != '~' in for loop itself, Remove while loop.

Instead of your looping method, Try this-

    for(i = 0; i < N && input != '~'; i++)
    {
        text[i] = input;
        scanf(" %c", &input); // Note the space before ' %c'
        count++;
    }
    text[i]='\0'; // To make the last byte as null.

You need give a space before %c if you use it in loops, else you can read only N/2 input from the user!

It is due to \n after the input character. After your input when you hit enter \n is read as a next input, to avoid this give a space before %c!

Output( No space before %c )-

root@sathish1:~/My Docs/Programs# ./a.out 
Text:
q
w
e
r
t
y
~
Count = 12

Output( With a space before %c )-

root@sathish1:~/My Docs/Programs# ./a.out 
Text:
q
w
e
r
t
y
~
Count = 6

Note the count difference!

查看更多
淡お忘
4楼-- · 2019-10-10 08:16

You have 2 loops. If the first one is not elapsed (because you get less chars than N), you never return to the first one, when you test input. More than that, the last char you read will usually be a \n, so you won't get a ~in the first loop level

查看更多
登录 后发表回答