我试图将一段文字读入矩阵,使每个单词都是一个单独的元素。第一句占据第一行,第二句占据第二行,依此类推,每个字占据矩阵的不同列。请在c ++中
例如句子:
John likes apples
Jack likes apples
会给:
[John, likes, apples]
[Jack, likes, apples]
这是我的代码目前对此细分市场的看法。我添加了vector
,string
,iostream
和stdafx
标头。我需要的信息是从文本文件的第2行开始的每三行,所以第2,5,8行......
Map_Data.open("/Users/Josh/Desktop/PhD/programming/general/RomanianMapData.txt");
vector< vector<string>> child_node_list; // vector of strings that will hold the child node titles for each parent node
vector< vector<int>> edge_length; // vector of int that will hold the edge distances between the parent node and each child node
while (Map_Data.is_open()) // performs actions while file is open
{
while (getline(Map_Data, line_check)) // checks the number of lines in the txt file
{
number_lines++;
}
break;
}
Map_Data.close(); // close file so it can be reopened at the beginning to get information
n = number_lines/3; // number of cities
child_node_list.resize(n);
for ( int i = 0; i<n; i++)
{
child_node_list[i].resize(n-1);
}
string word;
int j = 0;
int m = 0;
for (int i = 0; i<number_lines; i++)
{
getline(Map_Data, word);
if (i == 1 || i % 3== 1) // shows only the lines with the children nodes on
{
//cout << word << endl; // prints the children nodes for each parent node if needed to check
child_node_list[j][m] == word;
//m++;
//j++;
}
}
代码更改: for(int i = 0; i
getline(Map_Data, word);
if (i == 1 || i % 3== 1) // shows only the lines with the children nodes on
{
stringstream stream(word);
for (m = 0; m = n-1; ++m)
{
stream >> word;
child_node_list[j][m] = word;
}
//j++;
}
}
答案 0 :(得分:1)
使用stringstream
。它像所有其他输入流一样工作,也就是说,使用>>
运算符将提取一个单词(并删除空格)。
#include <sstream>
...
// After rewinding Map_Data, using seekg() or open()
for (int i = 0; i<number_lines; i++)
{
getline(Map_Data, line_check);
if (i % 3 == 1)
{
std::stringstream stream(line_check);
for (m = 0; m < n - 1; ++m)
{
stream >> word;
cout << word << endl; // if needed to check
child_node_list[j][m] = word;
}
}
}