簡體   English   中英

當用戶在 C++ 的同一行中輸入字符串和整數時,如何拆分字符串和整數?

[英]How can I split string and integer when user input both the string and the integer in the same line in C++?

我在做第 8 天:字典和地圖。 我想我知道如何用 C++ 解決這個問題。 但是,當用戶在同一行中同時輸入字符串和整數時,我不知道如何拆分字符串和整數。 它們由兩個空格分隔。

在此處輸入圖片說明

只需從使用空格作為分隔符的std::cin流式傳輸它們:

int n;
std::cin >> n;
for (int i = 0; i < n; ++i) {
    std::string s;
    int a;
    std::cin >> s >> a;
    // process a and s
}

嘗試這樣的事情:

#include <iostream>
#include <vector>
#include <utility>
#include <string>
#include <sstream>
#include <algorithm>

int main()
{
    std::vector<std::pair<std::string, int>> phoneBook;

    int n;
    std::string line;

    std::getline(std::cin, line);
    std::istringstream(line) >> n;

    for (int i = 0; i < n; ++i)
    {
        std::getline(std::cin, line);
        std::string name;
        int phoneNumber;
        std::istringstream(line) >> name >> phoneNumber;
        phoneBook.push_back(std::make_pair(name, phoneNumber));
    }

    while (std::getline(std::cin, line))
    {
        auto iter = std::find_if(phoneBook.begin(), phoneBook.end(),
            [&](const std::pair<std::string, int> &entry){
                return (entry.first == line);
            }
        );
        if (iter != phoneBook.end())
            std::cout << iter->first << "=" << iter->second << std::endl;
        else
            std::cout << "Not found" << std::endl;
    }

    return 0;
}

現場演示

另一方面,如果電話簿中從來沒有任何重復的名字,請考慮使用std::map而不是std::vector

嘗試這樣的事情:

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

int main()
{
    std::map<std::string, int> phoneBook;

    int n;
    std::string line;

    std::getline(std::cin, line);
    std::istringstream(line) >> n;

    for (int i = 0; i < n; ++i)
    {
        std::getline(std::cin, line);
        std::string name;
        int phoneNumber;
        std::istringstream(line) >> name >> phoneNumber;
        phoneBook[name] = phoneNumber;
    }

    while (std::getline(std::cin, line))
    {
        auto iter = phoneBook.find(line);
        if (iter != phoneBook.end())
            std::cout << iter->first << "=" << iter->second << std::endl;
        else
            std::cout << "Not found" << std::endl;
    }

    return 0;
}

現場演示

您還可以使用標准函數scanf()C stdin獲取輸入,因為電話簿條目、姓名和號碼的輸入是空格分隔的。

所以,使用如下:

char name[<size>];
int num;
scanf("%s %d", &name, &num);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM