输入的文件包含以下数据:
Juan Dela Cruz 150.50 5
“ Juan Dela Cruz”是我想分配给字符串A的名称,
“ 150.50”是我想分配给浮点数B
的数字,5是我想分配给int C的数字。
如果尝试cin
,则由两者之间的空格分隔。
如果使用getline
,则将整行作为字符串获取。
正确的语法是什么?
如果我们分析字符串,则可以进行以下观察。最后,我们有一个整数。在整数前面,我们有一个空格。并在其前面显示浮点值。再次在那个空间里。
因此,我们可以简单地从字符串的后面看倒数第二个空格。这可以通过以下方式轻松实现
size_t position = lineFromeFile.rfind(' ', lineFromeFile.rfind(' ')-1);
我们需要一个嵌套声明,rfind
请参阅此处,版本3。
然后,我们用名称构建一个子字符串。从字符串的开始到找到的位置。
对于数字,我们将原始字符串的其余部分放入std::istringstream
,然后从那里简单地提取出来。
请查看下面的简单代码,其中只有几行代码。
#include <iostream>
#include <string>
#include <cctype>
#include <sstream>
int main() {
// This is the string that we read via getline or whatever
std::string lineFromeFile("Juan Dela Cruz 150.50 5");
// Let's search for the 2nd last space
size_t position = lineFromeFile.rfind(' ', lineFromeFile.rfind(' ')-1);
// Get the name as a substring from the original string
std::string name = lineFromeFile.substr(0, position);
// Put the numbers in a istringstream for better extraction
std::istringstream iss(lineFromeFile.substr(position));
// Get the rest of the values
float fValue;
int iValue;
iss >> fValue >> iValue;
// Show result to use
std::cout << "\nName:\t" << name << "\nFloat:\t" << fValue << "\nInt:\t" << iValue << '\n';
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句