我的文本文件是一个由逗号分隔的大整数列表。
E.g。 “1,2,2,3,3,4,1,3,4,10”。 每两个整数表示图中的顶点邻接。
我想创建一些读取文本文件的C ++代码,并将每两个整数识别为某种数据结构(例如,对于是/否相邻的布尔值)。
此外,我将创建一个使用这些邻接对该图表着色的类。能够让代码记住给出每个顶点的颜色或值(这不仅仅是让程序解析文本文件中的数据),但是对此的帮助将被理解或出现在后来的问题。
我将如何在C ++中执行此操作?
答案 0 :(得分:0)
假设输入文件是由以逗号作为分隔符的整数列表组成的一行。 似乎主要步骤是:
示例:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
int main() {
fstream inFile;
inFile.open("input.txt"); // File with your numbers as input.
string tempString = "";
getline(inFile, tempString); // Read in the line from the file.
// If more than one line per file you can put this whole thing in a loop.
stringstream ss(tempString); // Convert from a string to a string stream.
vector<string> numbers_str = vector<string> (); // string vector to store the numbers as strings
vector<int> numbers = vector<int> (); // int vector to store the numbers once converted to int
while(ss.good()) // While you haven't reached the end.
{
getline(ss, tempString, ','); // Get the first number (as a string) with ',' as the delimiter.
numbers_str.push_back(tempString); // Add the number to the vector.
}
// Iterate through the vector of the string version of the numbers.
// Use stoi() to convert them from string to integers and add then to integer vector.
for(int i=0; i < numbers_str.size(); i++)
{
int tempInt = stoi(numbers_str[i], nullptr, 10); // Convert from string to base 10. C++11 feature: http://www.cplusplus.com/reference/string/stoi/
numbers.push_back(tempInt); // Add to the integer vector.
}
// Print out the numbers ... just to test and make sure that everything looks alright.
for(int i = 0; i < numbers.size(); i++)
{
cout << i+1 << ": " << numbers[i] << endl;
}
/*
Should be pretty straight forward from here.
You can go iterate through the vector and get every pair of integers and set those as the X and Y coor for your
custom data structure.
*/
inFile.close(); // Clean up. Close file.
cout << "The End" << endl;
return 0;
}
如果您的文件有多行,那么您可以扩展它并对文件中的每一行执行相同的操作。
希望有所帮助。