我在Main中有一个函数(int,string):
string word("HELLO");
int x = 0;
char choice;
swap(x, word);
我正在尝试传递以下函数,但没有成功:
void swap(int, string) {
int x = 0;
string word = "HELLO";
cout << "Would you like to change a letter? Please enter the letter
position. " << endl;
cin >> x;
if (x == 1) {
cout << "What do you want to change it to?" << endl;
cin >> word[0];
我一直收到这个错误:
错误C2664&#39; void std :: swap(std :: exception_ptr&amp;,std :: exception_ptr&amp;)throw()&#39;:无法从&#39; int&#39;转换参数1到&#39; std :: exception_ptr&amp;&#39;
是什么给出了?
答案 0 :(得分:0)
代码的主要问题是缩进。您的代码不可读,而且很难理解它。美化它。写出漂亮,可读和结构化的代码。您可以在以下链接中阅读有关缩进的更多信息。
接下来是函数声明。在定义函数之前,不要声明函数。函数声明应该是main
函数的顶部,函数的定义应该在main
函数之下。
您可以在以下链接中找到有关函数声明的更多信息:
由于您没有使用char array
打印string
,因此通过循环访问string
是没用的。添加<string>
库并开始使用string
类型。通过在string
内传递std::cout
变量就足以打印出string
。
最后,由于您试图在string
函数之外操作main
变量,因此需要传递引用参数。
void myFunction(std::string& parameter);
这样,将改变主要内部或任何其他函数内部的原始变量。如果没有引用&
,您尝试修改的值将不会更改。
以下链接演示了参考的使用。
http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/
请阅读下面我为什么要应用某些更改的评论。我对change
函数进行了狡猾的更改。您现在有资格为任何人工作
任意大小的string
类型。
#include <iostream>
#include <string> //When you are working on strings, use the string library.
using namespace std;
//Function declaration is very important. Have the declarations above main.
void change(string&);
int main() {
string word("HELLO");
char choice;
cout << "The word is : " << endl;
cout << word << endl;
//No need for the for loop to print out the string as
// we are working on a string and not a char array.
// for (int i = 0; i < word.length(); i++) {
// cout << word[i];
// }
change(word);
cout << "The new word is" << endl << word << endl;
cout << "Would you like to enter another change ? Enter Y or N ? " << endl;
cin >> choice;
if (choice == 'y' || choice == 'Y') {
change(word);
cout << word << endl;
}
else {
cout << "Good Bye" << endl;
}
system("pause");
return 0;
}
//When your datatype is to be modified outside the function, use the reference
//parameter type '&'.
//Without the reference type, your modified version of the type will only be modified
//inside that function.
//The original one will not be altered.
void change(string& word) {
/*
* size_t is simply unsigned int, to work towards manipulation and accessing
* of string types, use unsigned int or std::size_t
*/
size_t x = 0;
cout << "Would you like to change a letter? Please enter the letter position. " << endl;
cin >> x;
//Check to see if the inputted value is within the string length range.
if(x > 0 && x <= word.length())
cout << "What do you want to change it to?" << endl;
else{
cout << "The entered position is outside the string size range\n";
return; //Quit from the function if the condition is not met.
}
/*
* Instead of using if/else if statements,
* Just make a normal loop. Much simpler.
*/
for(size_t i = 0; i < word.length(); i++){
if((x-1) == i)
cin >> word[i];
}
}