c++ - 如何检查一行中的第二个字符串是否为数字?
问题描述
我使用 c++ 作为我的编程语言。我正在尝试检查 line 的第二个字符串值是否是使用isstringstream
将其转换为int
.
检查字符串的第一个值很容易,因为它是第一个值,但是如何检查字符串的第二个值是否为 int。我几乎没有学过getline()
,所以我宁愿方法不太复杂。
我一直在使用 if 语句,但似乎没有任何效果。
44 68 usable BothMatch
100 90 usable BothMatch
110 120 usable BothMatch
183 133 usable BothMatch
170 140 usable BothMatch
188 155 usable BothMatch
解决方案
一种可能性是使用 astd::istringstream
在每一行上获取单个单词。遍历每个单词时,增加一个计数器,以跟踪已处理的单词数。
如果需要处理每一行的第二个字,则必须检查计数器值是否等于 1(假设移动到新行时,计数器初始化为 0)。
由于您提到可以检查给定字符串是否为数字,因此我没有提供该isNumber()
函数的实现。
下面有一些源代码打印每一行+每个单词,“模拟”对你的isNumber()
函数的调用,每个第二个单词(在输入的每一行上)。
#include <iostream>
#include <sstream>
#include <string>
bool isNumber(const std::string& s) {
// TODO
return true;
}
int main() {
std::string s;
std::string word;
int lineNum = 0;
int wordNum = 0;
while (std::getline(std::cin, s)) {
std::cout << "Line number " << lineNum << ": " << s << "\n";
std::istringstream iss(s);
wordNum = 0;
while (iss >> word) {
std::cout << "\tWord number " << wordNum << " in line "
<< lineNum << ": " << word << "\n";
if (wordNum == 1 && isNumber(word))
std::cout << "'" << word << "' is a number\n";
wordNum++;
}
lineNum++;
}
return 0;
}
推荐阅读
- xml - 将xml转换为cpp的批处理文件
- azure - 如何找出 Azure 虚拟机的参考对象 ID?
- node.js - 无服务器部署中的自签名证书错误
- javascript - 如何使用 Vuex 在 Tabulator 中添加索引?
- python - 使用python检查名称是否存在文件夹
- node.js - 如何访问从 app.js 到模型节点 js 的 express-myconnection 数据库连接
- jquery - jQuery $.post 函数不能异步工作
- node.js - 从我的 api-url 启动 google vm 实例并通过特定的 URL-api 端点运行特定的命令
- plotly-dash - 如何在滑块选择器上添加标签
- python - 高效合并大量 pyspark DataFrames