1

このようなテキストファイルがあるとしましょう

6 3
john
dan
lammar

私は数字を読むことができ、名前は別のファイルにある場合にのみ読むことができます。ただし、ここでは番号と名前が 1 つのファイルに含まれています。最初の行を無視して、2 行目から直接読み始めるにはどうすればよいですか?

int main()
{
vector<string> names;
fstream myFile;
string line;
int x,y;
myFile.open("test.txt");
    //Im using this for reading the numbers
while(myFile>>x>>y){}
//Would use this for name reading if it was just names in the file
while(getline(myFile,line))
    names.push_back(line);
cout<<names[0];
return 0;
}
4

3 に答える 3

1

私があなたを正しく理解したかどうかはわかりませんが、常に最初の行をスキップしたい場合は、単にスキップできますか?

int main()
{
    vector<string> names;
    fstream myFile;
    string line;
    int x,y;
    myFile.open("test.txt");
    //skip the first line
    myFile>>x>>y;
    //Would use this for name reading if it was just names in the file
    while(getline(myFile,line))
    names.push_back(line);
    cout<<names[0];
    return 0;
}
于 2012-12-12T19:01:38.740 に答える
0

fstreamを使用している場合は、ignore()メソッドを呼び出すだけです。

istream&  ignore ( streamsize n = 1, int delim = EOF );

とても簡単になりました:

ifstream file(filename);
file.ignore(numeric_limits<streamsize>::max(), '\n');    // ignore the first line

// read the second line
string name; getline(flie, name);
于 2012-12-12T19:01:19.363 に答える
0

次のようなことを試してください:

int main()
{
    std::vector<std::string> names;
    std::fstream myFile;
    myFile.open("test.txt");
    if( myFile.is_open() )
    {
        std::string line;

        if (std::getline(myFile, line))
        {
            std::istringstream strm(line);

            int x, y;
            strm >> x >> y;

            while (std::getline(myFile, line))
                names.push_back(line);
        }

        myFile.close();

        if( !names.empty() )
            std::cout << names[0];
    }
    return 0;
}
于 2012-12-12T19:09:32.807 に答える