首页 > 解决方案 > 从文件中读入一个数组

问题描述

我正在尝试从文件读取到数组中。我知道我需要阅读,直到我打到一个空格(' '),然后当我打到行尾时('\n')跳到下一行。我不知道该怎么做。我尝试阅读直到(array != ' '),但这似乎不起作用。有小费吗?

输入:

销售员月计划撰写

看蓝天

猫穿过跑

顶部跌至

无论何时水是白色的

查尔斯检查欢呼便宜

湛蓝的天空

一对保罗彼得菲利普

阿黛尔·卡里·大卫·伊莱恩

桌椅床狗

标签: c++visual-c++

解决方案


这是读取文件的正确 C++ 方式。此代码逐行读取所需文件并将单词存储到向量中。您可以在自己的应用程序中将其用作参考。

#include <fstream>
#include <iostream>
#include <vector>
#include <sstream>

int main (int argc, char *argv[])
{
    std::vector<std::string> words;

    std::ifstream inFile;

    inFile.open("text.txt");
    if (!inFile) {
        std::cerr << "Failed to open file" << std::endl;
        return -1;
    }

    std::string input;

    /* read file line by line */
    while(std::getline(inFile, input)) {
        std::stringstream ss{input};
        std::string word;

        /* read words separated by space*/
        while (ss >> word) {
            words.push_back(word);
        }
    }

    std::cout << "Printing words in file" << std::endl;

    for(auto &word : words) {
        std::cout << word << std::endl;
    }

    return 0;
}

推荐阅读