最常见的读入数据方法集锦
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                最常见的读入数据方法集锦
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                我在程序編寫過程中,經常會遇到讀入數據的問題,大概這類問題分為兩種,一種是從控制臺讀取,一類是從文件讀取,我這里收集了一些常見的讀取方法,以供參考。
控制臺讀取:
情景一、有一個程序要求我們輸入一個數組,數組的個數已給定或者要求先給出個數,然后輸入數據。
代碼:
#include <iostream> #include <cmath> #include <vector> using namespace std;int main() {cout << "請輸入數組的個數" << " ";int n;cin >> n;int *a = new int[n];for (int i = 0; i < n;i++){cin >>a[i];}cout << "輸入的數據為" << " ";for (int i = 0; i < n; i++){cout <<a[i] << " ";}delete[]a;a = nullptr;return 0; }情景二、不斷輸入數字,然后求和分析:這個問題的難點在于不知道輸入數組的個數。當你輸入數字或者字符串后,回車,按ctrl+z結束輸入
代碼:
#include <iostream> #include <cmath> #include <vector> using namespace std;int main() {cout << "Enter numbers: ";int sum = 0;int input;while (cin >> input)sum += input;cout << "Last value entered = " << input << endl;cout << "Sum = " << sum << endl;return 0; }輸入: Enter numbers: 45 78 45 ^Z Last value entered = 45 Sum = 168 請按任意鍵繼續. . .#include "iostream" #include "string" using namespace std; int main() {string word;while (getline(cin, word))cout << word << endl;return 0; }
 
輸入:
 
或者:
#include <iostream> #include <iterator> #include <algorithm> #include <vector> #include <string> using namespace std; int main() {istream_iterator< string > is(cin);istream_iterator< string > eof;vector< string > text;copy(is, eof, back_inserter(text));sort(text.begin(), text.end());ostream_iterator< string > os(cout, " ");copy(text.begin(), text.end(), os);return 0; }輸入: acsnkalc acnkasm ^Z acnkasm acsnkalc 請按任意鍵繼續. . .
情景三、讀入如下格式的數據:
3 ? ? 5 ? ? ?6
5 ? ?6 ? ? ? 7
5 ? ?4 ? ? ? 4
即多行數據,每行數據間以空格隔開。
#include <iostream> #include <vector> #include <sstream> #include <string> using namespace std;int main() {vector<string> stringlist;string str;cout << "請輸入數字,每行三個" << endl;while (getline(cin,str)){stringlist.push_back(str);}int data;for (int i = 0; i < stringlist.size();i++){stringstream s(stringlist[i]);s >> data;cout << data<<" ";s >> data;cout << data << " ";s >> data;cout << data << endl;}return 0; }輸入: 請輸入數字,每行三個 1 5 6 2 3 4 7 5 6 ^Z 1 5 6 2 3 4 7 5 6 請按任意鍵繼續. . .
 從文件讀取:
 
情景一、同樣是上述數據,讀入文本數據,并輸出。
 
 3 ? ? 5 ? ? ?6
5 ? ?6 ? ? ? 7
5 ? ?4 ? ? ? 4
#include <iostream> #include <fstream> #include <iterator> #include <iostream> #include <vector> #include <sstream> #include <string> using namespace std;int main() {vector<string> stringlist;string str;ifstream infile("inputfile.txt");while (getline(infile, str)){stringlist.push_back(str);}int data;for (int i = 0; i < stringlist.size(); i++){stringstream s(stringlist[i]);s >> data;cout << data << " ";s >> data;cout << data << " ";s >> data;cout << data << endl;}return 0; }
參考文獻:
1.如何判斷cin輸入結束?
2.【C++】輸入流cin方法
3.C++ stringstream介紹,使用方法與例子
 
 
 
 
 
總結
以上是生活随笔為你收集整理的最常见的读入数据方法集锦的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 【C++深度剖析教程19】前置操作符与后
- 下一篇: 免费中文api文档!免费java帮助文档
