【问题标题】:Read text file into vector (double, double, string)? C++将文本文件读入向量(双精度、双精度、字符串)? C++
【发布时间】:2015-09-30 17:23:43
【问题描述】:

我有一个使用纬度经度位置名称的文本格式 ,例如:

41.3333 34.3232 Old Building

我必须读取这个文本文件(从命令行),用空格分隔每一行,使用stodlatlong 转换回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);
}

问题:

  1. 我能否对如何继续实施有所了解?

答案:从这里我需要查看文件中的每一行并用空格分割它们,然后将文件存储在一个向量中。所以文本文件的第一个数字是纬度,第二个经度,第三个(字符串)是位置。

【问题讨论】:

  • 您可以先考虑 fstream 的输入及其各自的语法。
  • stringstream ss(argv[1]); 只将文件名而不是文件内容放入ss
  • 可以::operator&gt;&gt;重载Distance

标签: c++ file text vector double


【解决方案1】:

这些是您最终使用 C++ 时的一些一般要点:-

  1. 尽可能避免使用指针。首选引用或复合类(如字符串)代替 char *。

  2. C++ 在线参考可以帮助您非常轻松地找到正确的用法。

  3. GDB 可以在大多数情况下帮助您解决问题中的问题。

按照 cmets 中的建议,您必须先读取字符串流中的文件,然后才能解析它。我还没有编译下面的代码,但我希望它能给你一个关于如何做到这一点的好主意。在这种情况下,文件是标准输入。您可以通过以下方式阅读:-

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);
}

【讨论】:

    猜你喜欢
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 2015-04-10
    相关资源
    最近更新 更多