gpt4 book ai didi

c++ - 从字符串中提取不同数据类型的变量

转载 作者:行者123 更新时间:2023-11-30 03:54:29 26 4
gpt4 key购买 nike

我正在尝试在这里处理文件 IO。我能够做基本的事情,但有点用完了这里的想法。我想从文本文件中读取输入。文本文件的每一行都遵循以下格式:<int> <char> <string literal> <float> , 如果不是,则忽略。

对于每一行,我们需要将变量存储为四种数据类型:

int i;
char c;
std::string s;
float f;

然后打印出来。对于下一行,它们将被覆盖并再次打印。

这是我的尝试:

int main() {
int i;
char c;
std::string s, x;
float f;
ifstream in;
in.open("Input.txt");
if(in) {
std::getline(in,x);
// How do I extract i, c, s and f components from x now?
cout << "\nInteger:" << i << ", Character: " << c << ", String: "
<< s << ", Float: " << f << endl;
}
return 0;
}

PS:尽管存在效率瓶颈,请仅使用基本概念来解决此问题,不要使用高级概念。

最佳答案

你可以简单地做:

while(in >> i >> c >> s >> f)
{
cout << "\nInteger:" << i << ", Character: " << c << ", String: "
<< s << ", Float: " << f << endl;
}

如果您的值是逗号分隔的,您可以使用 std::stringstream/std::getline 组合来解析标记(std::getline 允许指定一个分隔符),像这样:

std::stringstream ss; // from <sstream>
int field = 0;
while (std::getline(in, ss, ','))
{
switch (field)
{
case 0:
ss >> i;
break;
case 1:
ss >> c;
break;
case 2:
ss >> s;
break;
case 3:
ss >> f;
break;
}
if(++field == 4)
field = 0;
}

或者,您可以读取整行,删除逗号 (std::remove_if),将转换后的行发送到 stringstream,然后执行 ss >> i >> c >> s >> f.

关于c++ - 从字符串中提取不同数据类型的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29500704/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com