-5

getline を使用してファイルから行を読み込んでから、各行を表示しようとしています。ただし、出力はありません。入力ファイルは lorem ipsum ダミー テキストで、各文に改行があります。これが私のコードです:

#include <vector>
#include <string>
#include <fstream>
#include <iostream>

using namespace std;

int main() {

    string line;
    vector<string> theText;
    int i = 0;
    ifstream inFile("input.txt");

    if(!inFile)
        cout << "Error: invalid/missing input file." << endl;
    else {
        while(getline(inFile, line)) {
            theText[i] = line;
            theText[i+1] = "";
            i += 2;
        }

        //cout << theText[0] << endl;
        for (auto it = theText.begin(); it != theText.end() && !it->empty(); ++it)
            cout << *it << endl;
    }
    return (0);
}
4

3 に答える 3

2
vector<string> theText;
...
while(getline(inFile, line)) {
    theText[i] = line;
    theText[i+1] = "";
    i += 2;
}

最初の行は空のベクターを宣言します。アイテムを追加するにはpush_back()、単にインデックスに割り当てるのではなく、 を呼び出す必要があります。ベクトルの終わりを過ぎたインデックスへの代入は不正です。

while(getline(inFile, line)) {
    theText.push_back(line);
    theText.push_back("");
}
于 2013-08-19T21:35:22.913 に答える
1

ベクターpush_backに使用thetext

空のベクターにインデックスを付けています

   while(getline(inFile, line)) {

        theText.push_back(line);
        theText.push_back("\n");
    }

!it->empty()forループからも削除

    for (auto it = theText.begin(); it != theText.end() ; ++it)
        cout << *it << endl;

-std=c++0xまたは-std=c++11オプションを使用してコンパイルします。

于 2013-08-19T21:36:05.473 に答える