简体   繁体   中英

How can I read a text file and get a string from every line in C++?

So; I'm trying to create kind of a hangman game, and I want to get the words from a .txt file I have downloaded from the internet with about 4900 words, each one in a different line. I'm trying to read the file, but the program exits every time with the error(1), that is no file found. I've tried using absolute path, and also placed the file in the working directory and used the relative path, but every time I get the same error. Could anyone take a look and tell me what's wrong with this? I'm new in C++, I started learning with Java and now I want to try something new, so I'm not sure if there are some mistakes on the structure of the code. Thanks everyone!

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <vector>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;

vector<string> GetWords(){
    ifstream readLine;
    string currentWord;
    vector<string> wordList;

    readLine.open("nounlist.txt");

    while (getline(readLine, currentWord)) {
        wordList.push_back(currentWord);
    }


    if (!readLine) {
        cerr << "Unable to open text file";
        exit(1);
    }
    return wordList;
}

You have checked readLine after reading all data. You may use the following code:

if (readLine.is_open()) {
    while (getline(readLine, currentWord)) {
        wordList.push_back(currentWord);
    }
    readLine.close();
} else {
    cerr << "Unable to open text file";
    exit(1);
}

is_open function is to check if readLine is associated with any file.

Use this code,

std::ifstream readLine("nounlist.txt", std::ifstream::in);
if (readLine.good())
{
    while (getline(readLine, currentWord)) 
    {
        wordList.push_back(currentWord);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM