[英]How to convert string array to integer array in C++?
I have a string of non-uniform space separated integers,I want to do some arithmetic operations on the elements so I have decided to first convert the string to integer array.我有一串非均匀空格分隔的整数,我想对元素做一些算术运算,所以我决定先将字符串转换为 integer 数组。 Below is my approach:以下是我的方法:
string s; //let s="1 2 30 54 899 2 7 3 1";
cin>>s;
int n=s.length();
vector<int>arr(n);
for(int i=0;i<n;i++)
{
if(s[i]==' ')continue;
else{
arr.push_back(s[i]-'0');
}
}
for(int i=0;i<n;i++)
{
cout<<arr[i]<<endl; // arr should be{1,2,30,54,899,2,7,3,1};
}
What is wrong in this approach?这种方法有什么问题?
What is wrong in this approach?这种方法有什么问题?
operator>>
only extracts until the first encountered character in std::cin
that satisfies std::isspace()
, so s
could not possibly be initialized to a string containing spaces in your program. operator>>
仅提取直到std::cin
中第一个遇到满足std::isspace()
的字符,因此s
不可能在程序中初始化为包含空格的字符串。n
should be the length of the array.您假设字符串n
的长度应该是数组的长度。 The number of characters is not equal to the number of whitespace-separated values.字符数不等于空格分隔值的数量。arr
to length n
and then use push_back()
.您将arr
初始化为长度n
,然后使用push_back()
。 You should be default initializing the vector so it starts empty.您应该默认初始化向量,使其开始为空。push_back()
each digit as a separate element.您从字符串中分别读取每个字符,并且push_back()
每个数字作为单独的元素。 You can use std::getline()
to initialize the string from std::cin
and std::istringstream
to simplify extracting the formatted integers:您可以使用std::getline()
从std::cin
和std::istringstream
初始化字符串,以简化提取格式化整数:
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
int main()
{
std::string s;
std::getline(std::cin, s);
std::istringstream iss(s);
std::vector<int> arr;
for (int i; iss >> i;) {
arr.push_back(i);
}
for(auto& v : arr)
{
std::cout << v << std::endl;
}
}
You 'll loop all elements and convert with stoi
.您将循环所有元素并使用stoi
进行转换。 Then put it in the int-array.然后将其放入 int-array 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.