简体   繁体   English

我如何扫描带有单词和数字的字符串,但将其放在不同的数组中

[英]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.

相关问题 C ++如何扫描用户的字符串输入中的特定单词? - C++ How can I scan the user's string input for a specific word/words? 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词 - Given an array of words and a string, how can I count all words in a given string 我如何接受一个字符串输入,用每个空格分隔它并将每个单词放入一个数组中,然后对单个单词进行检查? - How do i take a string input, separate it by every space and put every word into a array, to then do checks on the individual words? 如何将$(SRCROOT)放入字符串中? - How can I put $(SRCROOT) into a string? 我们如何取出字符串数组或字符串中的多个 integer 数字并将它们分配给不同的 int 数据类型? - How can we take out the multiple integer numbers in the string array or string and assign them to different int data type? 我怎样才能找到最大的数字串? - How can I find the biggest string of numbers? 扫描字符串并将它们放入向量中 - scan string and put them in vectors 如何比较字符串数组中的单词? - How can you compare words within a string array? 有没有办法可以在“.structurevariable”前面放置一个字符串数组成员? - Is there a way I can put a string array member in front of “.structurevariable”? 我不能在开关中放置字符串,也不能在类中放置数组 - I can't put a string in a switch nor an array in a class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM