解析字符串输入并将其转换为 int C++
parse and convert string input to int c++
>输入:(一些数字,一些数字)示例:(12,2345235)我将如何解析此存储为字符串的输入并将其转换为整数?
是否可以创建从"("到","的字符串
然后另一个数字将从","开始并结束")"
这样,无论输入有多大,它都会被存储。
此外,如果输入为:坏字符(12,324)坏字符只要正确的输入在字符串中的某个地方,您仍然能够检索 12 和 324 并将它们存储为整数吗?
const int SIZE=100;
char input[SIZE]
// Read the input into the string.
fgets(input, SIZE-1, stdin);
// Extract the integers out of it.
int n1;
int n2;
sscanf(input, "(%d,%d)", &n1, &n2);
您可以尝试使用 scanf 系列,例如,如果字符串来自文件:
主.cpp
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream ifs ("test.txt", ifstream::in);
char buf[256];
int i1, i2;
while (ifs.getline(buf, 256)) {
sscanf(buf, "(%i,%i)", &i1, &i2);
cout << i1 << " " << i2 << endl;
}
ifs.close();
return 0;
}
输出
12 2345235
相关文章:
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 是否可以从int转换为enum类类型
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 功能样式转换从 'int' 到 'ItemType' 的匹配转换
- 将 int 数组转换为 std::vector<int*>
- 如何转换 int 变量并附加到常量 wchar_t*
- 类型转换<int>的舍入问题
- 在Objective-C中调用sqlite3数据库时,如何调用和转换int/NSNumber
- 转换 int -> 无符号长 长 是否由标准定义
- 简单的 int 到字符串转换..int to const char* 无效
- 如何将转换 int 除法键入为浮点数
- C++类型转换 int * 到类
- 预期的类型说明符,并且无法在初始化时转换“int*”
- 转换int并将其与char*连接
- 字符串流在转换int型时添加新行
- 转换int为字符串/char c++ /Arduino
- c# P-Invoke:如何转换INT fun(BYTE *bStream, UINT16 *nCount, const
- 类型转换(int**)和int(*)的区别
- 从"int"到"nodeType"的无效转换<int>
- 从无符号int构造对强制转换int的引用