一旦到达行尾,停止向2D数组中输入文本
C++ Stop inputting text into 2D array once it reaches the end of the line
我搜索了一遍,又读了一遍,但还是不明白。我只是试图输入一个文本文件到一个[I][j]字符串数组。它做得很好,但是我需要它在到达行尾时停止向数组输入并开始将第二行放到第二个数组中,在行尾停止等等。
我的文件包含4个独立的行,如下所示:
这是第一行
这是第二行。
这是第三行。
这是第四行。
我的代码读取它,并主要做我需要它做的事情。但是它将所有内容放入数组中,直到空间用完,然后继续到下一行。一旦到达第一行,它就不会停止。这是我的代码。
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string arrayTextIn[25][25];
ifstream textIn;
textIn.open("sampleText.txt");
for(int i=0; i<25; i++)
for(int j=0; j<25; j++)
{
textIn >> arrayTextIn[i][j];
if(arrayTextIn[i][j] == "n") //This is where I dont know how to proceed.
break;
}
for(int i=0; i<25; i++)
for(int j=0; j<25; j++)
cout << i << " " << j << " "<< arrayTextIn[i][j] << endl;
return 0;
}
这是输出,但我想要的是每行从新的[第i]行开始。谢谢你的帮助。
0 0这个
1是
0 2 line
1 .
0 4这个
5 .
0 6 line
2 .
0 8这个
9是
0 10 line
3 .
0 12这个
13是
0 14 line
4 .
16 0
1 0
1
1 2
1 3
4
这是一个两步的过程。
第一步是读取输入,一次一行,这将是读取输入文件中的每行文本:
ifstream textIn;
textIn.open("sampleText.txt");
for(int i=0; i<25; i++)
{
std::string line;
if (std::getline(textIn, line).eof())
break;
// Magic goes here.
}
那么,到目前为止,我们所完成的就是读取每一行输入,最多读取25行
第二步是取每一行输入,并将其分成以空格分隔的单词。
std::istringstream iline(line);
for(int j=0; j<25; j++)
{
std::string word;
if ((iline >> word).eof())
break;
arrayTextIn[i][j]=word;
}
首先构造一个istringstream
,它的工作原理与ifstream
完全相同,只是输入流来自字符串。
然后,它几乎和你最初的一样,只是现在作用域变小了,可以很容易地用一个循环来处理。
总之:处理任何中等复杂程度的任务的方法是将其分成两个或多个较小的任务。在这里,您将这个相对复杂的任务转化为两个更小、更容易实现的任务:首先,读取每一行文本,其次,给定一行已读文本,将每行划分为单独的单词。
如果你真的想保持你的设计(2D-array),那么这可能是一个快速的解决方案:
for (int i = 0; i < 25; i++) {
std::string line;
std::getline(textIn, line); // read the entire line
if (textIn.eof()) {
// if reach the end of file, then break the cycle.
break;
}
if (line.size() > 0) { // avoid empty lines
int j = 0;
size_t finder;
// Cycle and looking for whitespace delimiters.
while (finder = line.find(' '), finder != std::string::npos && j < 25) {
// get a single word
auto token = line.substr(0, finder);
if (token != " ") {
// if that word is not a simple white-space then save it in the array. You can also std::move if C++11
arrayTextIn[i][j] = token;
++j;
}
// erase that part from the main line
line.erase(0, finder + 1);
}
}
}
相关文章:
- 2D数组来自文本输入,中间有空格
- 如何使用用户输入在C++中正确填充2D数组
- 如何在C++中检查2D数组中负值的输入验证
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何在C++函数中声明静态 2D 数组?
- 我已经阅读了很多关于 2d 数组的信息,但我在作业中使用它时遇到了麻烦
- 使用矢量将文本文件中的输入存储到 2D 数组中
- 获取 2D 数组 c++ 中的所有数字对
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 如何在构造函数中使用初始值设定项设置具有相同值的 2d 数组?
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 如何创建一个所有行大小不同的 2D 数组,并且用户将指定每行将有多少个元素?
- 使用指针算法修改函数中的 2D 数组
- 在C++中初始化和打印 2D 数组
- 有没有办法使用输入的维度初始化 2d 数组中的所有项目而不循环C++?
- C++ 2D 数组写入多个位置
- 检测到堆损坏:在正常块 c++ 动态 2D 数组之后
- 如何从initializer_list初始化 2D 数组
- 交换函数不是在 C++ 中交换 2D 数组的元素