簡體   English   中英

如何在C ++中從文本文件中讀取字符

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

我想知道是否有人可以幫我弄清楚如何用C ++逐字逐句地讀取文本文件。 這樣,我可以有一個while循環(雖然還有文本),我將文本文檔中的下一個字符存儲在臨時變量中,這樣我可以用它做一些事情,然后用下一個字符重復該過程。 我知道如何打開文件和所有內容,但temp = textFile.getchar()似乎不起作用。 提前致謝。

你可以嘗試類似的東西:

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

@cnicutar和@Pete Becker已經指出了使用noskipws / unsetting 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)。

引用Bjarne Stroustrup:“>> >>運算符用於格式化輸入;即,讀取預期類型和格式的對象。如果不希望這樣,我們想要將字符作為字符讀取然后檢查它們,我們使用get () 職能。”

char c;
while (input.get(c))
{
    // do something with c
}
    //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.

Re: textFile.getch() ,你做了那個,或者你有一個說它應該工作的引用? 如果是后者,請擺脫它。 如果是前者,請不要這樣做。 得到一個很好的參考。

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

沒有理由不在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
}

這是一個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();
}

假設tempchartextFilestd::fstream派生...

你正在尋找的語法是

textFile.get( temp );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM