How to Read from a Text File, Character by Character in C++

后端 未结 8 1803
孤街浪徒
孤街浪徒 2020-12-06 10:17

I was wondering if someone could help me figure out how to read from a text file in C++, character by character. That way, I could have a while loop (while there\'s still te

相关标签:
8条回答
  • 2020-12-06 10:50
        //Variables
        char END_OF_FILE = '#';
        char singleCharacter;
    
        //Get a character from the input file
        inFile.get(singleCharacter);
    
        //Read the file until it reaches #
        //When read pointer reads the # it will exit loop
        //This requires that you have a # sign as last character in your text file
    
        while (singleCharacter != END_OF_FILE)
        {
             cout << singleCharacter;
             inFile.get(singleCharacter);
        }
    
       //If you need to store each character, declare a variable and store it
       //in the while loop.
    
    0 讨论(0)
  • 2020-12-06 10:54

    To quote Bjarne Stroustrup:"The >> operator is intended for formatted input; that is, reading objects of an expected type and format. Where this is not desirable and we want to read charactes as characters and then examine them, we use the get() functions."

    char c;
    while (input.get(c))
    {
        // do something with c
    }
    
    0 讨论(0)
提交回复
热议问题