Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 解析字符串并将其转换为数字_C++ - Fatal编程技术网

C++ 解析字符串并将其转换为数字

C++ 解析字符串并将其转换为数字,c++,C++,我有一个输入文件,我正在用基本的myFile>>变量读取它,因为我知道它的格式,而且格式总是正确的。我正在读取的文件格式为指令,为了使>工作,我将所有内容都作为字符串读取。若我有3个变量,每一行中有一个变量,那个么如何将字符串(例如)转换为int 1呢?我知道字符串的第一个和最后一个字符是需要删除的括号,然后我可以把它转换成int,但是我是C++的新成员,并且想知道一些最佳的方法(查找和移除,然后铸造到int)首先得到中间字符,你可以做 char Mychar=IncString。在(1);。然

我有一个输入文件,我正在用基本的
myFile>>变量
读取它,因为我知道它的格式,而且格式总是正确的。我正在读取的文件格式为
指令
,为了使
>
工作,我将所有内容都作为字符串读取。若我有3个变量,每一行中有一个变量,那个么如何将字符串(例如)转换为int 1呢?我知道字符串的第一个和最后一个字符是需要删除的括号,然后我可以把它转换成int,但是我是C++的新成员,并且想知道一些最佳的方法(查找和移除,然后铸造到int)

首先得到中间字符,你可以做<代码> char Mychar=IncString。在(1);<代码>。然后你可以做
intmyint=(int)myChar

即使您删除了
字符,您仍然可以使用
>
将文件内容导入到字符串中,因此您仍然需要将其转换为int。如果只有1个值,您可以按照Nicholas Callahan在上一个答案中所写的进行操作,但是如果您有多个字符,您希望将其读取为int,你别无选择,只能施放。

使用stringstream

#include <string>
#include <sstream>
#include <iostream>

int main() {
    std::string str = "<1>";
    int value;
    std::stringstream ss(str);
    char c;

    ss >> c >> value >> c;

    std::cout << value;
}
#包括
#包括
#包括
int main(){
std::string str=“”;
int值;
std::stringstream ss(str);
字符c;
ss>>c>>值>>c;

std::cout您也可以求助于
sscanf

#include <cstdio>
#include <iostream>
#include <string>

int main()
{
    std::string str = "<1234>";
    int value;
    sscanf(str.c_str(), "<%d>", &value);
    std::cout << value << std::endl;
}
#包括
#包括
#包括
int main()
{
std::string str=“”;
int值;
sscanf(str.c_str(),“”,&value);

std::不可能复制不正确的,也可能使用C样式转换。上面的stringstream答案更好,还可以包装在模板函数中。但它并不总是一位数。我正在尝试使用.erase()在字符串上删除第一个和最后一个迭代器以删除,但它没有像我预期的那样工作。明白了,这是有效的,最初我将
值作为字符串,它没有删除最后一个
,但我更改了它,它工作了。谢谢!