【问题标题】:Process text file by C++ -- extract a certain string from text file用 C++ 处理文本文件——从文本文件中提取某个字符串
【发布时间】:2011-03-10 14:52:12
【问题描述】:

我是 C++ 的新手。 我有一个文本文件,其内容如下:

Systemname    localtesthost
SystemIp      X.X.X.X
Systemowner   root
...

现在我要提取“Systemname”的值,即“localtesthost”。

我可以提取包含“Systemname localtesthost”的行,但我不知道如何提取字符串“Systemname”。

以下是我的程序需要帮助:

const char* configInfoFile = "config_info";//the text file name
ifstream ifs(configInfoFile);
    string line;
    while(getline(ifs,line)) {
        if(line.length() > 0){
            int index = line.find("SystemName");
            if (index != -1)
            {

                                .
                                .

            }

        } 
}

谁能告诉我如何提取字符串"localtesthost"

非常感谢!

【问题讨论】:

    标签: c++ string getline substr strtok


    【解决方案1】:

    这是一种方法:

    1. 使用您刚刚读入的行创建一个std::istringstream
    2. 从流中读取两个std::string 对象,键和值
    3. 如果键与您要查找的内容匹配,则值应包含您需要的内容。

    【讨论】:

    • Nim,感谢您的方法。这比我想象的要简单得多。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多