简体   繁体   English

C ++:按制表符拆分字符串,但包含空格

[英]C++: String splitting by tabs, but include spaces

I am working on a client/server program using sockets and I am trying to parse the input file. 我正在使用套接字在客户机/服务器程序上工作,并且试图解析输入文件。 I have a struct to store the Majors, the early career pay, and the mid-career, respectively. 我有一个结构来分别存储专业,职业早期薪水和职业中期。 The client program asks the user to input the name of the major and the server program returns both salaries. 客户端程序要求用户输入专业名称,而服务器程序将同时返回这两个工资。

The issue with the input file is this: 输入文件的问题是这样的:

Geophysics 54100 122200 地球物理学54100 122200

Cognitive Science 54000 121900 认知科学54000 121900

Electrical Power Engineering 68600 119100 电力工程68600 119100

They are all separated as Major[TAB]Pay[Tab]Pay, and the majors have spaces in them. 它们全都作为Major [TAB] Pay [Tab] Pay分开,并且各专业之间都有空格。 I want to store each of them in the struct. 我想将它们每个存储在结构中。

Any solution to this? 有什么解决办法吗?

You can use the third argument in getline() to say what character to stop at. 您可以在getline()使用第三个参数来说明要停止的字符。 The default is \\n , but you can also specify that it is \\t to have it stop at the tab you want: 默认值为\\n ,但是您也可以指定\\t使其停止在所需的选项卡上:

getline(std::cin, line, '\t');

Start with something this: 从以下内容开始:

ifstream f("c:\\temp\\test.txt");
string s;
while (getline(f, s))
{
    istringstream iss(s);
    string major, early, mid;
    getline(iss, major, '\t');
    getline(iss, early, '\t');
    getline(iss, mid, '\t');
    cout << major << '|' 
         << early << '|' 
         << mid   << endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM