cin读取不知行列数的矩阵以及带逗号的整型数据

    摘要:如果输入中给出了一个矩阵的具体的行列数,那很好办,循环读取就行了,如果没有给你具体的行列数,而且输入中的整型数据之间还有逗号,那应该怎么来读取呢?下面给出具体代码:

  一、输入没有给出矩阵的具体行列数的情况

 1     ifstream in("input.txt");
 2     string s;
 3     int count=0, count1=0;// 分别记录行数和元素个数
 4     while (getline(in, s))
 5     {
 6         istringstream is(s);
 7         int inter;
 8         while (is >> inter)// 读取每行的所有数据
 9         {
10             count1++;
11             cout << inter << " ";            
12         }
13         count++;
14         cout << endl;
15     }    
16     cout << count <<" "<<count1<< endl;
测试数据
1 2 6
1 3 1
1 4 5
2 3 5
2 5 3
3 4 5
3 5 6
3 6 4
4 6 2
5 6 6

 

 输出为:

即:总共有十行,共30个元素。

二、输入中带有逗号的情况

  只要把逗号换成空格就行了,代码如下:

 1     ifstream in("input.txt");
 2     string s;
 3     int count=0, count1=0;// 分别记录行数和元素个数
 4     while (getline(in, s))
 5     {
 6         for (int i = 0; i < s.size(); i++)// 如果输入中有‘,’,将其换成空格
 7             if (s[i] == ',')
 8                 s[i] =' ';
 9         istringstream is(s);// //把s中的字符串存入字符串流中   
       //cout << is.str() << endl;// str():使istringstream对象返回一个string字符串 
10 int inter; 11 while (is >> inter)// 读取每行的所有数据 12 { 13 count1++; 14 cout << inter << " "; 15 } 16 count++; 17 cout << endl; 18 } 19 cout << count <<" "<<count1<< endl;
测试数据
1,2,6
1,3,1
1,4,5
2,3,5
2,5,3
3,4,5
3,5,6
3,6,4
4,6,2
5,6,6
输出为:

    和上面的结果一样。

  

 

   总结:知道了行数和元素总个数,就能知道矩阵的行列数了!

  附:代码分析:

   ifstream in("input.txt");将对象与特定的文件关联起来。// #include<fstream>  // 里面定义了一个用于处理输出的ifstream类。

  getline(in, s);// 读取整行的输入,并丢弃换行符

  关于istringstream is(s);:

  C++引入了ostringstream、istringstream、stringstream这三个类,要使用他们创建对象就必须包含<sstream>这个头文件。
  istringstream类用于执行C++风格的串流的输入操作。
  ostringstream类用于执行C风格的串流的输出操作。
  strstream类同时可以支持C风格的串流的输入输出操作。

 

C++的输入输出分为三种:

(1)基于控制台的I/O

(2)基于文件的I/O

(3)基于字符串的I/O

 

posted @ 2018-04-02 10:55  ~君莫笑~  阅读(1491)  评论(0编辑  收藏  举报