c++ - 从文件中读入一个数组
问题描述
我正在尝试从文件读取到数组中。我知道我需要阅读,直到我打到一个空格(' ')
,然后当我打到行尾时('\n')
跳到下一行。我不知道该怎么做。我尝试阅读直到(array != ' ')
,但这似乎不起作用。有小费吗?
输入:
销售员月计划撰写
看蓝天
猫穿过跑
顶部跌至
无论何时水是白色的
查尔斯检查欢呼便宜
湛蓝的天空
一对保罗彼得菲利普
阿黛尔·卡里·大卫·伊莱恩
桌椅床狗
解决方案
这是读取文件的正确 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;
}
推荐阅读
- c# - 在 Visual Studio 中运行 Docker Compose 时引发异常
- javascript - 有没有办法使用三元的条件作为值?
- android - 从以前的活动中检索字符串
- php - laravel 和 jwt:总是返回 Unauthorized
- python - 查找不包括测试用例的 Python 代码总行数
- spring - 为什么我得到异常 - 没有足够的变量可用于在 Spring Rest URI 调用中扩展?
- eclipse - 上传文件后在spring boot中刷新文件夹
- jquery - 验证完成后如何禁用验证器?
- ios - 如何使用 iOS sdk 在运行时更改 AWS 的区域?
- r - Duckworth-Lewis-Stern 计算器计算修正后的目标