解析字符串输入并将其转换为 int C++

parse and convert string input to int c++

本文关键字:转换 int C++ 字符串 输入      更新时间:2023-10-16

>输入:(一些数字,一些数字)示例:(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