输入一行个数不等的数,或者一行字符串,按“Enter”结束,并将其保存。

从键盘输入一行数,按“Enter”结束

#include<vector>
#include<iostream>
#include<stdio.h>
using namespace dtd;
int main()
{
    vector<int>v;
    int a = 0;
    int c = 0;
    cin >> a;
    v.push_back(a);
    while (c = getchar() != '\n')
    {
        cin >> a;
        v.push_back(a);
    }
    for (int i = 0; i < v.size(); ++i)
        cout << v[i] << " ";
    system("pause");
    return 0;
}
输入一行字符串,保存起来;
#include<string>
int main()
{
    string str;
    getline(cin, str);

    cout << str << endl;
    system("pause");
    return 0;
}

(我们也可以将输入的字符串保存到字符数组vector中)

#include<string>
#include<vector>
#include<stdio.h>
using namespace std;
int main()
{
    vector<char> v;
    char ch = 0;

    while (ch != '\n')
    {
        scanf("%c", &ch);
        v.push_back(ch);
    }
    v[v.size() - 1] = 0;//把最后一个字符有'\n'改成'\0'
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/prefect_boy/article/details/80518239
今日推荐