C++输入问题探究

突发奇想对C++输入输出做一点研究,主要是做笔试题自己写输入老是花很多时间,所以做一个总结。

对于输入多行字符串,代码如下:

#include<iostream>
#include<string>
using namespace std;

int main() {
    int n;
    string s;
    cout << "please input row:" << endl;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> s;
        cout << s << endl;
    }
    return 0;
}

但是cin不能输入空格,如果用getline(cin,s),输入一行字符串后程序直接结束了,程序中间还留有空行,代码如下:

#include<iostream>
#include<string>
using namespace std;

int main() {
    int n;
    string s;
    cout << "please input row:" << endl;
    cin >> n;
    for (int i = 0; i < n; i++) {
        getline(cin, s);
        cout << s << endl;
    }
    return 0;
}

image

原因是因为换行符也被读入了,所以将换行符去掉,在cin>>n;后加上一句cin.ignore();结果如下图,

image

也可以将cin.ignore();换成getchar();但是要引用#include<cstdio>

#include<iostream>
#include<string>
using namespace std;

int main() {
    int n;
    char ch[256];
    cout << "please input row:" << endl;
    cin >> n;
    cin.ignore();
    for (int i = 0; i < n; i++) {
        gets_s(ch);
        cout << ch << endl;
    }
    return 0;
}

上面这种是采用gets_s();读取也是可行的,另外scanf(“%s”);读取字符串碰到空格和tab键会停下来

下面采用while循环的方式来存入整型数组,由于循环没有结束条件,会不断要求你输入直到达到数组最大上限,因此控制一个n值,然后跳出循环

#include<iostream>
using namespace std;

int main() {
    int num[100];
    int i = 0;
    int n = 3;
    while (cin>>num[i]) {
        cout << num[i] << endl;
        if (i >= n)  
            break; 
        ++i;
    }
    return 0;
}

最后说下向量的方式,向量是一种很好的数据结构,可以适当扩容,相比较数组要更节省空间,避免浪费多余资源

#include<iostream>
#include<vector>
using namespace std;
using std::vector;

int main() {
    int n;
    cin >> n;
    vector<int> nums;
    int input;
    while (cin>>input) {
        nums.push_back(input);
        if (nums.size() == n)  
            break;
    }
    for (int j = 0; j < n;++j) {
        cout << nums[j] << endl;
    }
    return 0;
}

image

从结果可以看出,存进向量里面的值受到我设定n的限制

参考:

https://blog.csdn.net/praker/article/details/37612029

posted @ 2019-03-19 10:02  薛定谔的哈士奇  阅读(226)  评论(0编辑  收藏  举报