Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/155.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++;str到int?_C++ - Fatal编程技术网

C++ 如何转换c++;str到int?

C++ 如何转换c++;str到int?,c++,C++,可能重复: 我让用户按顺序输入9个数字。我需要把字符串数字转换成整数 string num; int num_int, product[10]; cout << "enter numbers"; cin >> num; for(int i =0; i<10; i++){ product[i] = num[i] * 5; //I need the int value of num*5 } string-num; int num_int,乘积[10]; c

可能重复:

我让用户按顺序输入9个数字。我需要把字符串数字转换成整数

string num;
int num_int, product[10];

cout << "enter numbers";
cin >> num;

for(int i =0; i<10; i++){
   product[i] = num[i] * 5; //I need the int value of num*5
}
string-num;
int num_int,乘积[10];
cout>num;

对于(inti=0;i为什么不直接读取整数

int num;
cin >> num;
以下是完整的示例:

//library you need to include
    #include <sstream>
    int main()
    {
        char* str = "1234";
        std::stringstream s_str( str );
        int i;
        s_str >> i;
    }
//您需要包含的库
#包括
int main()
{
char*str=“1234”;
标准:stringstream s_str(str);
int i;
s_str>>i;
}

不需要有两个变量。C++中的转换通常是在 输入流,但从未将文本视为字符串。因此 你可以简单地写:

int num;
std::vector< int > product( 10 );

std::cout << "enter number: ";
std::cin >> num;

...
int-num;
标准:向量积(10);
std::cout>num;
...
请注意,我已经更正了将数组声明为 嗯,通常不会使用<代码> int乘积[10 ];C++中的<代码>。 (你几乎不会在同一行定义两个变量,
即使语言允许。)

如果您绝对必须使用
std::string
(出于任何其他原因..可能是家庭作业?),那么您可以使用
std::stringstream
对象将其从
std::string
转换为
int

std::stringstream strstream(num);
int iNum;
num >> iNum; //now iNum will have your integer
或者,您可以使用C中的
atoi
函数来帮助您完成此任务

std::string st = "12345";
int i = atoi(st.c_str()); // and now, i will have the number 12345
因此,您的程序应该如下所示:

vector<string> num;
string holder;
int num_int, product[10];

cout << "enter numbers";
for(int i = 0; i < 10; i++){
    cin >> holder;
    num.push_back(holder);
}
for(int i =0; i<10; i++){
   product[i] = atoi(num[i].c_str()) * 5; //I need the int value of num*5
}
向量数;
绳夹;
int num_int,乘积[10];
支架;
回推次数(支架);
}

对于(inti=0;i到目前为止,转换为字符串并再次转换的最简单方法是使用转换函数

 std::string s="56";
 int i=std::stoi(s);

回来

 int i=56;
 std::string s=std::to_string(i);

当然,如果你正在阅读输入,你也可以当场阅读

 int i;
 std::cin >> i;

这已经被问过很多次了。如果你想让用户输入一个数字,就让他们输入一个数字。你确定要
num[i]
?只访问
num
中的一个字符。这是一个非常好的答案,但我需要两个变量,一个字符串和一个int@user1082764为什么?为什么你需要一个字符串?需要注意的是,std::to_字符串是C++11的一个特性。并不是所有的编译器都有它。@Caesar我们还要说多久?直到时代C++程序使用它。@凯撒NAH,直到每个流行的OS上的免费编译器支持它的大部分,这或多或少现在。