zoukankan      html  css  js  c++  java
  • 连续多行输入--C++ 中字符串标准输入的学习及实验(续篇)

     
    编程中常常会用到连续多行输入的情况,如果事先知道要输入多少行的话,可以直接定义一个变量,然后用循环就可以实现了,但有时候事先并不知道,要输入多少行,于是就可以用到输入流碰到文件终止符的情况了,具体的操作就是ctrl+Z,然后按下回车键

    程序例1

     1 #include<iostream>
     2 #include<string>
     3 #include<vector>
     4 using namespace std;
     5 
     6 int main()
     7 {
     8     int num;
     9     vector <int>nums;
    10     while(cin>>num)
    11     {
    12         nums.push_back(num);
    13     }
    14     vector<int>::iterator it;
    15     for(it=nums.begin();it!=nums.end();it++)
    16     {
    17         cout<<(*it)<<endl;
    18     }
    19 
    20     return 0;
    21 }

    程序例2

     1 #include<iostream>
     2 #include<string>
     3 #include<vector>
     4 using namespace std;
     5 
     6 int main()
     7 { 
     8      string q;
     9     vector<string>save_q;
    10     while(getline(cin,q))
    11     {
    12         save_q.push_back(q);
    13     }
    14     vector<string>::iterator it;
    15     for(it=save_q.begin();it!=save_q.end();it++)
    16     {
    17         cout<<(*it)<<endl;
    18     }
    19     return 0;
    20 }

    程序例3

     1 #include<iostream>
     2 #include<string>
     3 #include<vector>
     4 using namespace std;
     5 
     6 int main()
     7 {
     8 
     9     char * p;
    10     vector<char *>save_p;  //为什么用char * 就不能存进去值
    11     p=new char[8];
    12     while(cin.getline(p,8))
    13     {
    14         save_p.push_back(p);
    15         p=new char[8];
    16     }
    17     vector<char *>::iterator it;
    18     for(it=save_p.begin();it!=save_p.end();it++)
    19     {
    20         cout<<(*it)<<endl;
    21     }
    22 
    23 
    24 
    25     return 0;
    26 }

    程序例4

     1 #include<iostream>
     2 #include<string>
     3 #include<vector>
     4 using namespace std;
     5 
     6 int main()
     7 {
     8 
     9     char p[100];
    10     //vector<char *>save_p;  //为什么用char * 就不能存进去值
    11     vector<string>save_p;
    12     while(cin.getline(p,8))
    13     {
    14         save_p.push_back(p);
    15         //cout<<p<<endl;
    16     }
    17     //vector<char *>::iterator it;
    18     vector<string>::iterator it;
    19     for(it=save_p.begin();it!=save_p.end();it++)
    20     {
    21         cout<<(*it)<<endl;
    22     }
    23 
    24     return 0;
    25 }

    上面是四组测试程序,全部通过,但是第4四组,刚开始不小心写成了注释掉的那几行,结果总是错误,后来发现原因是这样的,char p[100];
    是在编译的时候就已经确定了p的地址,所以每次输入的时候都是在往同一个地址对应的地方存值,导致vector<char *>里面存的值也都是同一个地址里面的数,所以每次存新值的时候都把前面的覆盖掉了。

  • 相关阅读:
    min-max 容斥
    集训作业
    UOJ Test Round 3
    uoj Goodbye Dingyou
    Codeforces Round #516 (Div. 1) 题解
    Codeforces Round #517(Div. 1) 题解
    概率论(Ⅱ)
    Berlekamp-Massey算法学习笔记
    多项式取模优化线性递推总结
    [ZJOI2019]线段树
  • 原文地址:https://www.cnblogs.com/bewolf/p/4377247.html
Copyright © 2011-2022 走看看