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

Tob*_*oby 13 c++ text file character

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

cni*_*tar 30

你可以尝试类似的东西:

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

  • @PeteBecker 是的,我喜欢它,因为这就是 `C` 在读取单个字符时所做的。 (2认同)

Jer*_*fin 11

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

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

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

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

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

要在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;});
Run Code Online (Sandbox Code Playgroud)

以这种方式完成工作,您将接收连续字符作为传递给(在本例中)lambda函数的参数的值(尽管如果您愿意,可以使用显式函子而不是lambda).


use*_*430 6

引用Bjarne Stroustrup的话:“ >>运算符用于格式化输入;即,读取预期类型和格式的对象。在不希望这样做的情况下,我们希望将字符读取为字符,然后检查它们,我们使用get () 功能。”

char c;
while (input.get(c))
{
    // do something with c
}
Run Code Online (Sandbox Code Playgroud)


mik*_*ike 5

    //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.
Run Code Online (Sandbox Code Playgroud)


Dr.*_*yll 5

这是一个 C++ 时尚的函数,您可以使用它逐个字符读取文件。

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();
}
Run Code Online (Sandbox Code Playgroud)


Pet*_*ker 2

回复:textFile.getch(),这是你编造的吗?或者你有参考资料表明它应该有效吗?如果是后者,那就摆脱它吧。如果是前者,就不要这样做。得到一个很好的参考。

char ch;
textFile.unsetf(ios_base::skipws);
textFile >> ch;
Run Code Online (Sandbox Code Playgroud)