如何使一个整数向量忽略空白,并在C++中的每个元素上加2

How to make an integer vector ignore white space and add 2 to every element in C++

本文关键字:元素 C++ 向量 整数 何使一 空白 并在      更新时间:2023-10-16

我有一个奇怪的问题,所以我的老师告诉我们使用向量创建一个简单的程序,该程序将首先询问用户要输入多少整数,在通过空格作为分隔符输入数字后,输出应为每个向量元素加2。

Ex-

How many numbers are you going to enter = 4 (Lets assume the user enters 4)
     Enter the numbers = 11 45 71 24 (Lets assume the user entered these 4 numbers)
THE OUTPUT SHOULD BE THIS = 13 47 73 26 (with spaces added 2)

由于使用矢量是必须的,我知道如何用普通整数矢量输出加2,但当它带有空格时,我不知道,到目前为止,我编写的程序将接受空间之前的所有内容,并将向其加2。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
    vector <int> userInput;
    int input;
    int number;
    int num1;
    cout << "How many numbers are you going to enter ? :";
    cin >> number;
    cout << "Enter the Numbers : " << endl;
    cin >> input;
    userInput.push_back(input);
    cout << "Vector Contains : ";
    for (unsigned int i = 0; i < userInput.size(); i++)
    {
        cout << userInput[i] + 2;
    }   
    system("pause>nul");
    return 0;
}

您只接受一个输入的原因是您只接受来自std::cin的一个int。其他int仍然保留在流中。你应该这样做:

while(/*we still have stuff to extract*/)
{
  std::cin >> input;
  userInput.push_back(input);
}

然而,我们仍然需要知道何时停止。由于我们只期望用户输入一行,因此我们可以执行std::cin.peek() != 'n'来检查我们是否已经达到用户先前按下Enter键的程度。

感谢您的阅读。

int的标准提取运算符需要空格作为项之间的分隔符,因此您不需要在其中做任何特殊的操作。只需读取int,将其放入向量中,进行加法运算,然后打印出结果。假设你已经阅读了n的计数,那么真正的工作可能看起来像这样:

std::copy_n (std::istream_iterator<int>(std::cin),
             n, 
             std::back_inserter(your_vector));
std::transform(your_vector.begin(), your_vector.end(),
               std::ostream_iterator<int>(std::cout, " "),
               [](int i){ return i + 2; });

尝试以下

#include <iostream>
#include <vector>
#include <cstdlib>
int main() 
{
    std::cout << "How many numbers are you going to enter ? :";
    size_t n = 0;
    std::cin >> n;
    std::vector<int> v( n );
    std::cout << "Enter " << n << " numbers : " << std::endl;
    int x;
    for ( size_t i = 0; i < n && std::cin >> x; i++ ) v[i] = x;
    for ( int x : v  ) std::cout << x + 2 << ' ';
    std::cout << std::endl;
    std::system( "pause>nul" );
    return 0;
}

如果要输入

4
11 45 71 24

输出将是

13 47 73 26 

另一种方法是使用标准函数std::getlinestd::istringstream而不是operator >>

例如

#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <sstream>
#include <limits>
int main() 
{
    std::cout << "How many numbers are you going to enter ? :";
    size_t n = 0;
    std::cin >> n;
    std::vector<int> v( n );
    std::cout << "Enter " << n << " numbers : " << std::endl;
    std::cin.ignore( std::numeric_limits<std::streamsize>::max(), 'n' );
    std::string s;
    std::getline( std::cin, s );
    std::istringstream is( s );
    int x;
    for ( size_t i = 0; i < n && is >> x; i++ ) v[i] = x;
    for ( int x : v  ) std::cout << x + 2 << ' ';
    std::cout << std::endl;
    std::system( "pause>nul" );
    return 0;
}