[英]how can i scan a string with words and numbers but put it on different array
for example, I have a string abc123(input always words first then numbers, there's no space between words and numbers)例如,我有一个字符串 abc123(总是先输入单词再输入数字,单词和数字之间没有空格)
I know that in c u can scan it separately like this我知道在 c 你可以像这样单独扫描
char words[10], numbers[10];
scanf("%[a-zA-Z]%[0-9]", words, numbers)
and the code will put abc to words and 123 to numbers代码会将 abc 转换为单词,将 123 转换为数字
is it possible to do like that in c++?在 c++ 中可以这样做吗? and how to do it?以及如何去做?
The following code reads a line upto the first new line (you may want to change it to space) and converts every character to number.以下代码读取一行直到第一个新行(您可能希望将其更改为空格)并将每个字符转换为数字。 If the conversion fails, it's a letter.如果转换失败,则为一封信。
#include <string>
#include <vector>
#include <iostream>
int main(){
std::string line;
std::vector<char> words;
std::vector<int> numbers;
while(std::getline(std::cin, line, '\n')){
for(const char c : line){
try{
numbers.push_back(std::stoi(std::string(1, c)));
}
catch( const std::invalid_argument &ex){
std::cout << ex.what() << ": " << c << std::endl;
words.push_back(c);
}
}
}
for(const auto t : numbers){
std::cout << t;
}
for(const auto t : words){
std::cout << t;
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.