如何在C ++中从文本文件中读取字符

时间:2012-09-02 21:50:34

标签: c++ file text character

我想知道是否有人可以帮我弄清楚如何用C ++逐字逐句地读取文本文件。这样,我可以有一个while循环(虽然还有文本),我将文本文档中的下一个字符存储在临时变量中,这样我可以用它做一些事情,然后用下一个字符重复该过程。我知道如何打开文件和所有内容,但temp = textFile.getchar()似乎不起作用。提前谢谢。

8 个答案:

答案 0 :(得分:29)

您可以尝试以下方式:

char ch;
fstream fin("file", fstream::in);
while (fin >> noskipws >> ch) {
    cout << ch; // Or whatever
}

答案 1 :(得分:10)

@cnicutar和@Pete Becker已经指出了使用noskipws /取消设置skipws一次读取一个字符而不跳过输入中的空格字符的可能性。

另一种可能性是使用istreambuf_iterator来读取数据。除此之外,我通常使用像std::transform这样的标准算法来进行阅读和处理。

例如,假设我们想要做一个类似Caesar的密码,从标准输入复制到标准输出,但每个大写字符加3,所以A将成为DB可能会变成E等等(最后,它会回绕,以便XYZ转换为ABC

如果我们要在C中这样做,我们通常会使用这样的循环:

int ch;
while (EOF != (ch = getchar())) {
    if (isupper(ch)) 
        ch = ((ch - 'A') +3) % 26 + 'A';
    putchar(ch);
}

要在C ++中做同样的事情,我可能会更像这样编写代码:

std::transform(std::istreambuf_iterator<char>(std::cin),
               std::istreambuf_iterator<char>(),
               std::ostreambuf_iterator<char>(std::cout),
               [](int ch) { return isupper(ch) ? ((ch - 'A') + 3) % 26 + 'A' : ch;});

以这种方式完成工作,你会收到连续的字符作为传递给(在这种情况下)lambda函数的参数的值(尽管你可以使用显式函子代替lambda)。

答案 2 :(得分:4)

    //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.

答案 3 :(得分:3)

引用Bjarne Stroustrup:“&gt;&gt;运算符用于格式化输入;也就是说,读取预期类型和格式的对象。这是不可取的,我们想要将字符作为字符读取然后检查它们,我们使用get()函数。“

char c;
while (input.get(c))
{
    // do something with c
}

答案 4 :(得分:2)

回复:textFile.getch(),你做到了吗,或者你有一个说它应该有效的参考?如果是后者,请摆脱它。如果是前者,请不要这样做。得到一个很好的参考。

char ch;
textFile.unsetf(ios_base::skipws);
textFile >> ch;

答案 5 :(得分:1)

没有理由不在C ++中使用C <stdio.h>,事实上它通常是最佳选择。

#include <stdio.h>

int
main()  // (void) not necessary in C++
{
    int c;
    while ((c = getchar()) != EOF) {
        // do something with 'c' here
    }
    return 0; // technically not necessary in C++ but still good style
}

答案 6 :(得分:1)

这是一个c ++时尚函数,可用于通过char读取char文件。

void readCharFile(string &filePath) {
    ifstream in(filePath);
    char c;

    if(in.is_open()) {
        while(in.good()) {
            in.get(c);
            // Play with the data
        }
    }

    if(!in.eof() && in.fail())
        cout << "error reading " << filePath << endl;

    in.close();
}

答案 7 :(得分:0)

假设tempchartextFilestd::fstream衍生产品......

您正在寻找的语法是

textFile.get( temp );
相关问题