0

How can i use scanf to read string with blank space(without enter)? And i also want this program to stop whenever input is EOF.

I used the following code:

int main()      //this is not the whole program
{
    char A[10000];
    int length;

    while(scanf(" %[^\n]s",A)!=EOF);
    {
        length=strlen(A);
        print(length,A); 
        //printf("HELLO\n");
    }


    return 0;
}

But it is reading two EOF(ctrl+Z) to stop the program.can anyone give me any suggestion?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
mahin hossen
  • 175
  • 9
  • 1
    Well to begin with the format `"%["` end with the `"]"`. That `"s"` you have is not part of the format specifier, and the [`scanf`](https://en.cppreference.com/w/c/io/fscanf) function want to match it explicitly. Also [`scanf`](https://en.cppreference.com/w/c/io/fscanf) does only return `EOF` if there's an error or actual end-of-file, not when it fails to match the format. – Some programmer dude Nov 30 '18 at 12:56
  • 1
    Oh and I should probably have started with: ***How*** is it "acting weirdly"? For some specified input, what it the expected behavior and output? And what is the *actual* behavior and output? Also please read about [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly learn how to create a [mcve]. – Some programmer dude Nov 30 '18 at 12:58
  • it is reading two EOF(ctrl+Z) to stop the program – mahin hossen Nov 30 '18 at 13:02
  • 2

1 Answers1

1

it is reading two EOF(ctrl+Z) to stop the program

No. You may be pressing ^Z twice, yet scanf() is only "reading" one end-of-file EOF. That is just how your keyboard/OS interface works. Research how to signal end-of-file.

Other changes

char A[10000];
// while(scanf(" %[^\n]s",A)!=EOF);
// Drop final `;`  (That ends the while block)
// Add width limit
// Compare against the desired result, 1, not against one of the undesired results, EOF
// Drop the 's'
while(scanf(" %9999[^\n]", A) == 1) {
    length=strlen(A);
    // print(length,A); 
    print("%d <%s>\n", length, A); 
    //printf("HELLO\n");
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • Thanks for the suggestion. **Can you please explain "scanf(" %9999[^\n]", A) == 1)" ?** I am new to c programming.It might be helpful – mahin hossen Nov 30 '18 at 14:58
  • 1
    @mahinhossen Review [C library function - scanf()](https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm), [Scansets in C](https://www.geeksforgeeks.org/scansets-in-c/) and let me know what remains to explain. – chux - Reinstate Monica Nov 30 '18 at 16:43