我有以下代码来查找输入的大小,并从输入中提取整数:
void getInteger(string s) {
stringstream str_strm;
str_strm << s;
string temp_str;
int temp_int;
while (!str_strm.eof()) {
str_strm >> temp_str;
if (stringstream(temp_str) >> temp_int) {
cout << temp_int << "";
}
temp_str = "";
}
}
int main()
{
string myString;
int totalChar;
getline(cin, myString);
int stringLength = myString.length();
cout << stringLength << endl;;
getInteger(myString);
}
如何将 getInteger 值存储到变量中,以便可以将其值与整数进行比较/求和?例如,输入为:
我爱6
因此,代码应计算输入的总字符数和整数:
8 + 6 = 14
答案 0 :(得分:0)
如果您有一个函数将提取一个整数并将该整数包含在.length()
和该整数的输出中,请在函数本身中形成所有输出,而不是使事情复杂化并失去控制通过执行main()
中的部分输入以及函数中的一部分来确定初始输入。
通过这种方式处理事情,您可以在一个函数中完全控制输出。例如,在您的情况下,如果找不到整数,您将如何“取消输出”长度?
将这些更改放在适当的位置,您的功能可能类似于:
void getint (std::string s)
{
int val, /* var to hold int value */
found = 0; /* flag indicating if int was found */
size_t len = s.length(); /* get length of s */
std::string tmp; /* temporary string to read into from ss */
std::stringstream ss (s); /* create stringstream from string */
while (ss >> tmp) { /* read from ss */
try { /* stoi must have exception handler */
val = stoi (tmp); /* attempt conversion */
found = 1; /* on success set found flag */
break; /* break loop */
}
catch (const std::exception & e) { /* catch exception get next word */
continue;
}
}
if (found) /* if integer found, output your sum */
std::cout << len << " + " << val << " = " << len + val << '\n';
else /* otherwise handle error */
std::cerr << "error: no integer value in input.\n";
}
(注意:,如果不进行任何转换,唯一的错误处理就是获取下一个单词。任何输出都只会在输入和所需输出之间添加行)
使用该功能的示例程序可以是:
#include <iostream>
#include <sstream>
#include <string>
void getint (std::string s)
{
int val, /* var to hold int value */
found = 0; /* flag indicating if int was found */
size_t len = s.length(); /* get length of s */
std::string tmp; /* temporary string to read into from ss */
std::stringstream ss (s); /* create stringstream from string */
while (ss >> tmp) { /* read from ss */
try { /* stoi must have exception handler */
val = stoi (tmp); /* attempt conversion */
found = 1; /* on success set found flag */
break; /* break loop */
}
catch (const std::exception & e) { /* catch exception get next word */
continue;
}
}
if (found) /* if integer found, output your sum */
std::cout << len << " + " << val << " = " << len + val << '\n';
else /* otherwise handle error */
std::cerr << "error: no integer value in input.\n";
}
int main (void) {
std::string s;
if (getline (std::cin, s))
getint (s);
else
std::cerr << "stream error or user canceled.\n";
}
使用/输出示例
$ ./bin/lengthaddition
I love 6
8 + 6 = 14
输入中没有整数
$ ./bin/lengthaddition
I love B
error: no integer value in input.
仔细检查一下,如果还有其他问题,请告诉我。