c++ - 当 C++ 中的数据不一致时,将文本文件中的数据读入二维数组
问题描述
有人告诉我使用 2D 数组来读取下面文件的所有内容并将其存储在 2D 数组中。这是文件:
People often say that motivation doesn t last Well neither does bathing that s why we recommend it daily Ziglar
Someday is not a day of the week Denise Brennan Nelson
Hire character Train skill Peter Schutz
Your time is limited so don t waste it living someone else s life Steve Jobs
Sales are contingent upon the attitude of the salesman not the attitude of the prospect W Clement Stone
Everyone lives by selling something Robert Louis Stevenson
If you are not taking care of your customer your competitor will Bob Hooey
The golden rule for every businessman is this: Put yourself in your customer s place Orison Swett Marden
If you cannot do great things do small things in a great way Napoleon Hill
*上面是一个包含数据的文本文件
该文件有很多随机空间,但我可以cin
用来忽略它们。我感到困惑的部分是每一行都有不同数量的列要处理,所以我不能简单地使用嵌套的 for 循环。
最后,我希望能够cout << data[0][1];
并且它应该“经常”打印出来。行本质上是单词的行号。
解决方案
您可以使用 getline 然后使用 stringstream 来读取单词。
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main() {
ifstream input;
string line;
string word;
string data[3][10]; //You need to dynamically allocate memory if you don't know the size of your input. I am doing this to keep it short
input.open("input.txt");
int i = 0;
while(getline(input, line)) { //Reading file line by line until the end of file
stringstream ss(line);
int j = 0;
while(ss) {
ss >> word; //word will become the next string in your line (People, often, say...)
data[i][j] = word;
j++;
}
i++;
}
return 0;
}
你会得到
cout << data[0][0] -> "People"
cout << data[0][1] -> "often"
.
.
etc.
推荐阅读
- android - 有没有办法我们可以从 Linux 的终端下载 Sdk 命令行工具?
- android - 浮动操作按钮在相对布局中不浮动
- c# - C# 套接字编程。允许 2 个应用程序使用相同的套接字/TCP 连接
- git - 如何 repo 初始化本地 .git 和本地 manifest.xml
- sql-server - SQL 存储过程中的 Unicode
- c# - 在 ASP.NET MVC 中的网页上显示 Word 和 Excel 文件
- javascript - 您好,我如何使用 javascript 打开另一个 html
- ruby-on-rails - Rails 6 API + React + Google login:登录后如何授权用户访问某些服务器路由?
- java - 为什么此代码为相同的输入提供两个不同的输出?
- python - pandas.to_datetime() 的格式