读取文本文件到矢量(双,双,字符串)?c++
Read text file into vector (double, double, string)? C++
我有一个文本格式,使用纬度, 经度和位置名称,例如:
41.3333 34.3232 Old Building
我必须读取这个文本文件(从命令行),用空白分隔每行,使用stod
将lat
和long
转换回double
,然后将整个文件读取为矢量或列表。
这是我目前卡住的地方:
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
class Distance{
public:
double x;
double y;
string location;
};
int main(int argc, char *argv[]){
// If the user didn't provide a filename command line argument,
// print an error and exit.
if (argc <= 1){
cout << "Usage: " << argv[0] << " <Filename>" << endl;
exit(1);
}
char *pFilename = argv[1];
string buf; // Have a buffer string
stringstream ss(argv[1]); // Insert the string into a stream
vector<string> tokens; // Create vector to hold our words
while (ss >> buf)
tokens.push_back(buf);
}
问题:
- 我能对如何继续实施有一些见解吗?
回答:从这里我需要看看文件中的每一行,并通过空格分割它们,然后将文件存储在一个向量中。所以文本文件的第一个数字是纬度,第二个是经度,第三个(字符串)是位置。
当你最终使用c++时,这些是一些一般的要点:-
-
尽量避免使用指针。
首选引用或复合类,如string代替char *。 c++在线参考可以帮助你很容易地找到正确的用法
GDB可以在大多数情况下帮助您解决您的问题。
正如注释中所建议的,您必须首先读取字符串流中的文件,然后只有您才能解析它。我没有编译下面的代码,但我希望它能给你一个关于如何做到这一点的好主意。在本例中,该文件是标准输入。您可以通过以下方式读取:-
char buffer[1000]; // assumine each line of input will not be more than this
while(cin.getline(buffer , 1000)) // constant 1000 can be moved to a MACRO
{
// cin does not eat up the newline character. So we have to do something like this to make it work
cin.ignore (std::numeric_limits<std::streamsize>::max(), 'n');
//discard characters until newline is found
stringstream ss(buffer); // Insert the string into a stream
vector<string> tokens; // Create vector to hold our words
string buf ;
Distance distance ;
ss>>buf;
distance.x = stod(buf);
tokens.push_back(buf);
ss>>buf;
distance.x = stod(buf);
tokens.push_back(buf);
ss>>buf;
distance.x = buf;
tokens.push_back(buf);
}