我有一个使用纬度、经度和位置名称的文本格式 ,例如:
41.3333 34.3232 Old Building
我必须(从命令行)读取这个文本文件,用空格分隔每一行,使用 stod
转换 lat
和 long
返回到 double
,然后将整个文件读入 vector 或列表。
这就是我目前所坚持的:
#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);
}
问题:
- 我能否了解如何继续实现?
回答:从这里我需要查看文件中的每一行并用空格分隔它们,然后将文件按它们的内容存储在一个 vector 中。所以文本文件的第一个数字是纬度,第二个是经度,第三个(字符串)是位置。
最佳答案
当你最终使用 C++ 时,这些是一些通用的要点:-
如果可以,请避免使用指针。首选引用或复合类(如字符串)代替 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);
}
关于c++ - 将文本文件读入 vector ( double 、 double 、字符串)? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32872198/