我有一個非常簡單的問題。
我有一個如下專案:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
string file_name;
cin >> file_name;
ifstream file(file_name);
if(file.good()){
cout << "File can be loaded";
}
else{
cout << "Default file will be loaded";
}
return 0;
}
在命令列中,如果我只是敲擊Enter鍵盤,我不想讀取任何內容file_name,然后它會自動加載默認檔案。目前的情況是它會等到我輸入一些東西。
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
operator>>首先丟棄前導空格(除非在skipws流上禁用標志),然后讀取直到遇到空格。Enter生成一個'\n'字符,該字符operator>>被視為空白。
對于您想要做的事情,請std::getline()改用,例如:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
string file_name;
getline(cin, file_name);
if (file_name.empty()) {
file_name = "default name here";
cout << "Default file will be loaded" << endl;
}
else {
cout << file_name << " will be loaded" << endl;
}
ifstream file(file_name);
if(file.is_open()){
cout << "File is opened" << endl;
}
else{
cout << "File is not opened" << endl;
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/524691.html
標籤:C 壳命令
