0
我正在嘗試編寫練習中的程序Bjarne Stroustrup編程原理與實踐使用C++該程序應該是一個名爲Bulls and Cows的小遊戲,用戶嘗試猜測四位數字。這是我的代碼至今:std_lib_facilities.h編譯練習時出現C++錯誤
#include "../Library/std_lib_facilities.h"
class string_error{};
/*
* Method to determine if an integer is
* in a vector
*/
bool contains(vector<int> v,int k){
}
int string_to_int(string s){
if(s == "0") return 0;
else if(s == "1")return 1;
else if(s == "2")return 2;
else if(s == "3")return 3;
else if(s == "4")return 4;
else if(s == "5")return 5;
else if(s == "6")return 6;
else if(s == "7")return 7;
else if(s == "8")return 8;
else if(s == "9")return 9;
else throw string_error();
}
int main(){
/*
* There is an int vector with the numbers
* of the answer in it
*
* There is also an int vector with the numbers
* of the user's guess
*
* User inputs a four digit integer that is read as
* a string called str_guess
*
* for each digit in the guess string the digit is
* converted to an integer and added to the guess vector
*
* The guess vector is then run through for each digit in the vector
* each digit is checked against the answer at the same index
* if the digit in the answer at that index number is not the same as the
* digit in the guess vector then the digit is checked if the answer
* vector contains it at all
*
* for each number that is correct for both the value and position
* 1 is added to the bull value
* for each number that is within the answer value but not in the correct position
* 1 is added to the cow value
*
* The bull and cow values are displayed after the user enters their guess
*
* The user is prompted for a guess until their guess returns 4 bulls
*/
vector<int> answer;
answer.push_back(7);
answer.push_back(9);
answer.push_back(2);
answer.push_back(4);
string str_guess = "";
cout << "Enter a four digit integer as a guess";
cin >> str_guess;
vector<int> guess;
for(int i = 0; i < 4; i++){
int guess_digit = string_to_int(str_guess[i]);
guess.push_back(guess_digit);
}
cout << "Length of guess vector: " + guess.size();
}
正如你可以看到我使用Mr.Stroustrup的頭文件std_lib_facilities.h(here)不幸的是,每當我嘗試編譯我的程序我得到這個錯誤:
In file included from ../Bulls_and_Cows.cpp:13:
../../Library/std_lib_facilities.h:106:38: error: no matching constructor for initialization of 'std::string' (aka 'basic_string<char, char_traits<char>, allocator<char> >')
template<class S> String(S s) :std::string(s) {}
我在使用eclipse和mac os gcc編譯器的mac上。任何幫助你可以提供我將不勝感激。謝謝
哇哦,這是愚蠢的我。謝謝你現在的工作 –
對於你的另一個問題,出於某種原因,當我試圖實例化向量答案(或任何其他向量)時,它會返回一個錯誤,當我嘗試使用列表格式。例如。矢量 answer = {7,9,2,4}不起作用。你有什麼猜測爲什麼? –
這是一個C++ 11語法,它通過初始化器列表構造對象。要使用它,您需要在編譯時設置標誌「-std = C++ 11」。例如。 'g ++ -std = C++ 11 -o main main.cpp'。如果您使用IDE,請查看編譯器設置。 –