次のプログラムをテストしています。ここでは2つの入力が関係しています。最初はintのベクトル、2番目はintです。
main.cppにファイルは以下の通りです:BashからのC++ cinへの2つの入力
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void print(vector<int> & vec) {
for (vector<int>::iterator it = vec.begin(); it != vec.end(); ++it)
cout << *it << " ";
cout << endl;
}
int main() {
vector<int> nums{};
int i;
int target;
cout << "Please enter a vector of integers:\n";
while (cin >> i) {
nums.push_back(i);
}
cout << "Vector of Integers:" << endl;
print(nums);
cin.clear();
cout << "Please enter an integer:" << endl;
cin >> target;
cout << "Checking whether " << target << " is in the vector...\n";
if (find(nums.begin(), nums.end(), target) != nums.end()) {
cout << "Target found!\n";
}
else {
cout << "Target not found!\n";
}
return 0;
}
bashスクリプト
$ g++ -std=c++11 main.cpp
は私のコードをコンパイルし、フォルダ内のA.EXEを作成します。 次に、Iはバッシュでそれを開こう:私はベクトルNUMSの= {1,2,3}でテスト
$ ./a.exe
、あなたが見ることができるように、それは、第二のCINがスキップされることが判明以下。
Please enter a vector of integers:
1 2 3 EOF
Vector of Integers:
1 2 3
Please enter an integer:
Checking whether 0 is in the vector...
Target not found!
ただし、Bash端末の助けを借りずに直接a.exeを開いても問題ありません。それで、Bashの下でスムーズに動くようにいくつかの変更を加えることは可能ですか?
ありがとうございます!
P.私はWin7を使用します。
ありがとうございました!現在のプログラムはうまく動作します。プロセスを終了させるために、 "eof"のような何かを "無効"に読みかける必要があるようです。しかし、すべてのintの文字列を自分のコードに置き換えた後、どのように "\ n"や "\ r"を試しても機能しません。彼らはどちらも文字列と見なされていると思います。この状況でBashに有効なEOFオプションがありますか?cmdの "^ z"に相当しますか?私はBashにとって本当に新しいです。 – user285827
文字列を読みたい場合は、空白以外の文字を文字列に読み込むことができるため、別のアプローチをとる必要があります。 'std :: getline'を使ってテキスト行を読み込み、' std :: istringstream'を使って行の内容をベクトルに読み込むことができます。 –