简体   繁体   中英

Why wont my input from scanf print correctly?

My program scans from input and prints all the capital letters used.

Im trying to print the original input from stdin at the end of my program too.

But when i use printf, it seems to skip the first part of the input expression, printing the remaining stuff in my character array. Please help me see where the problem lies. -comments in code-

#include <stdio.h>

int main(void){

char input[81];
int letters[91];
int i;

    //initialize arrays input and letters
for (i = 0; i < 90; i++) letters[i] = 2;
for (i = 0 ; i < 80; i++) input[i] = 'a';
i = 0;  

    //reads into input array until EOF
while((scanf("%c",input)!= EOF)){

    //checks input for characters A-Z 
    if((input[i]>= 'A' && input[i]<= 'Z'))


       letters[input[i]] = 1;
    }

    //prints capital letters from input that occur at least once
for(i = 'A'; i < 'Z'; i++){
    if (letters[i]==1)
    printf("%c", i);}        // this output works fine, the scan worked??


//print blank line
printf("\n\n");


// print input
printf("%s\n", input);      //This is where the incorrect output comes from.  

return 0;}

does my original input change? why? did my input not get scanned correctly in the first place? please respond quickly!

Here:

while((scanf("%c",input)!= EOF)){

you're only ever reading characters into input[0] . This is fine for what you're doing for letters , but obviously when you try to print out input , it's not going to work as you expect.

When you fix it, you'll also need to remember to add a terminating \\0 after the last input character.

The scanf loop reads your input one character at a time, and stores that one character in input[0] . When the scanf loop is completely finished, input[0] contains the last character read, and the rest of input is untouched.

To repair, you need to include i++ at the end of the scanf loop.

By the way, it would be clearer (and more efficient) to fill the input buffer with a single call to fgets then loop through the input buffer with: for (i=0; buf[i]!='\\0'; i++) { ... }

You must do

while((scanf("%c",&input[i])!= EOF))
{i++;}

instead of this

while((scanf("%c",&input)!= EOF))
{}

What you are doing is scan the character into the address of the first element int the array everytime, hence it gets overwritten again and again. Remaining part of the input[] array is not being accessed, and hence does not change

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM