C++ Could not convert input string when using cin and variables - c++

I'm trying to do a simple program where the user inputs a string with his/her name, then if the string is equal to a certain name, it executes different commands.
It's something like this:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string input = "";
cout << "What's your name?:\n>";
getline(cin, input);
if(input = "Micaela"){
cout << "You're the best" << input << endl << endl;
}
else
cout << "You kinda suck" << input << endl << endl;
return 0;
}
When compiling, I get the following error:
13 22 C:\Users\Francisco\Desktop\cpp\holanena.cpp [Error] could not convert 'input.std::basic_string<_CharT, _Traits, _Alloc>::operator=, std::allocator >(((const char*)"Micaela"))' from 'std::basic_string' to 'bool'

use == instead of =
== is for comparison
= is for assingment

The problem occurs in the line
if(input = "Micaela")
which assigns "Micaela" to input. Use comparison operator == instead of assignment operator = to get what you want:
if(input == "Micaela")

if(input = "Micaela") is an assignment. You want if(input == "Micaela") instead, which is a comparison.

Related

C++ Loop for String

I am struggling to create a loop for getting input from user. The input must push_back() each instance.
#include <iostream>
#include <array>
#include <cstring>
#include <vector>
#include <string>
#include <string.h>
using namespace std;
int main()
{
vector <string> bookQ = { "what","book","is","that","you","are","reading" };
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
string input;
int x = 0;
for (x != '1') { // require a loop to input string and end when user prompts
cout << "Enter 1 to stop" << endl; //
cin >> x; //
getline(cin, input); //
bookQ.push_back(input); //
} //
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}
Your for loop is missing the declaration and (iteration) expression parts:
for (declaration-or-expression; declaration-or-expression; expression)
so it should have looked like this:
for (;x != '1';) {
which is generally written as
while (x != '1') {
That would cause problems though since it would not stop directly when the user entered 1.
You are also comparing an int with a char ('1'), so in order to exit the loop, the user would have had to enter 49 (the ASCII value for 1), not 1.
You are also mixing formatted input (cin >> x) with unformatted input (getline). I suggest that you stick to one only.
Example:
while(cout << "Enter 1 to stop\n", getline(cin, input) && input != "1") {
bookQ.push_back(input);
}
Assuming you meant that input is a string, then you've made a few mistakes with types. First of all, you've used wrong type for variable x, you used int which is integer type, and the type string is required. Secondly, when comparing x with '1' you used single quotes, which define the type of variable as char, not string. To make 1 a string you should use double quotes, like so "1". Besides that, you have used for(condition), which is incorrect syntax. You should use while(condition). Also, when your loop iterates, the x variable is the input book name, and input variable is always an empty string, so I would suggest replace input with x everywhere. The working code is below.
P.S. I am not sure whether you want "1" to be in the final vector, so I haven't changed that
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> bookQ = {"what", "book", "is", "that", "you", "are", "reading"};
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
string input;
string x;
while (x != "1") {
cout << "Enter 1 to stop" << endl;
cin >> x;
bookQ.push_back(x);
}
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}
simply check if input is 1 everytime the user enters somthing, and when it does = 1, simply break loop.
string x;
while (true) { // require a loop to input string and end when user prompts
cout << "Enter 1 to stop" << endl;
cin >> x;
if (x == "1"){
break;
}
getline(cin, x);
bookQ.push_back(x);
}
}
First, your for syntax is wrong. You want a while loop instead, or in this case a do..while loop would make more sense. Also, you are pushing the user's input into the vector before validating what the input actually is.
Second, x is an integer, but '1' is a character whose ASCII value is number 49. Your loop will never end, because != will always be true. Since you want the user to enter number 1 to stop the loop, you need to drop the quotes:
Third, what is the point of pre-populating bookQ? Just declare the bookQ without any initial data, and then cout the entire question as a normal string. This way, after the user is done entering input, the vector will contain only the user's input and nothing else.
Try something more like this:
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
vector <string> bookQ;
string input;
cout << "what book is that you are reading" << endl;
do {
cout << "Enter a book, or 1 to stop" << endl;
getline(cin >> ws, input);
if (input == "1") break;
bookQ.push_back(input);
}
while (true);
for (size_t i = 0; i < bookQ.size(); ++i) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}

C++ count number of characters in a string

I am so close, I need to count the number of given characters in a given string. It needs to loop over and over again but i keep getting this error:
countchar.cpp:27:22: error: â was not declared in this scope
countchar.cpp:27:38: error: â was not declared in this scope
countchar.cpp:27:61: error: â cannot be used as a function
I really am not too familiar with the algorith of count but if someone could help out, that would be appreciated. Here is my code:
#include <string>
#include <fstream>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
char character;
string sentence;
char answer;
while(1) {
cout << "Enter a character to count the number of times it is in a sentence: ";
cin >> character;
cout << "Enter a sentence and to search for a specified character: ";
getline(cin, sentence);
if(character == '\n' || sentence.empty())
{
cout << "Please enter a valid answer:\n";
break;
}
else {
int count = count(begin(sentence), end(sentence), character);
cout << "Your sentence had" << count << character
<< "character(s)";
}
cout << "Do you wish to enter another sentence (y/n)?: ";
cin >> answer;
if (answer == 'n'){
break;
}
}
return 0;
}
The problem seems to be in this line:
int count = count(begin(sentence), end(sentence), character);
You declare a variable count and immediately after you use it as a function. You have to rename the variable (to, say, c) to use function std::count.
As for the remaining errors, you should use sentence.begin() instead of begin(sentence) and similarly sentence.end() instead of end(sentence).

Invalid array assignment?

When I run the code below I get the error : invalid array assignment on lines 14 and 26. I am fairly new (1 week) to c++ so I am a bit confused. I searched and could not find an answer to solve my problem.
#include <iostream>
int main()
{
using namespace std;
char usrname[5];
char psswrd[9];
cout << "Please enter your username:";
cin >> usrname;
if (usrname = "User")
{
cout << "Username correct!";
}
else
{
cout << "Username incorrect!";
}
cout << "Please enter your password:";
cin >> psswrd;
if (psswrd = "password")
{
cout << "The password is correct! Access granted.";
}
else
{
cout << "The password is incorrect! Access denied.";
}
return 0;
}
You can't assign arrays, and
usrname = "User"
does just that. Don't.
You meant
usrname == "User"
which is a comparison, but won't compare your strings. It just compares pointers.
Use std::string instead of char arrays or pointers and compare with ==:
#include <string>
//...
std::string usrname;
cin << usrname;
if (usrname == "User")
// ^^
// note == instead of =
Side question - what's the point of shortening "username" to "usrname"... you're saving a single character...
you need to use strcmp or similar.
if (!strcmp(usrname, "User"))
{
cout << "Username correct!";
}
what you are doing is assigning a value not comparing values.

I need to access a random .txt file, or a random line of a .txt file and out put it to the screen

What I am trying to do is create a (seemingly) random fact generator, by selecting a random .txt file, containing the fact, and outputting it to the screen. Here is the code:
#include <fstream>
#include <iomanip>
#include <iostream>
#include <cmath>
#include <ctime>
#include <string>
#include <vector>
#include "getQuestion.h"
using namespace std;
int main() {
int mainMenuChoice;
ifstream Bibliography;
//string easyBib;
char randomQuestion;
string easyBib;
string Questions /*[15]*/;
string Answers /*[15]*/;
ifstream inputFile;
//char newline = '\n';
//char chars;
//int linenum = 1;
string line;
char randomQ;
//cout << "%s by Noah" << endl;
cout << "Quiz Menu\n\n";
cout << "1. Play Game!\n";
cout << "2. Bibliography\n";
cout << "3. Developer Info\n";
//cout << "4. Admin Menu\n";
cout << "4. Exit\n";
cout << "Menu Choice: ";
cin >> mainMenuChoice;
switch (mainMenuChoice) {
case 1: {
srand ( time(NULL) );
randomQuestion = rand() % 10 + 1;
randomQ = '0' + randomQuestion;
randomQ = randomQ + '.txt';
inputFile.open(randomQ);
getline(inputFile, line);
vector<string> lines;
for( string line; getline(inputFile,line); )
{
lines.push_back(line);
}
size_t iRandLine = rand() % lines.size();
string randomLine = lines[iRandLine];
cout << "Line " << (iRandLine+1) << ": " << randomLine << endl;
break;
}
case 2: {
inputFile.open("Bib.txt");
//istream& getline (char* s, streamsize n, char \n )
inputFile >> easyBib;
cout << easyBib << endl;;
return(0);
}
case 3: {
cout << "Program made by: XXXX XXXXXXXX" << endl;
cout << "Mrs. XXXXXXX's Period 4 Social Studies Class" << endl;
break;
}
case 4: {
cout << "Thank you for playing!" << endl;
return(0);
}
default: {
cout << "Sorry, Invalid Choice!\n";
return(2);
}
}
return(0);
}
i am also getting this compiler error:
52: error: invalid conversion from 'char' to 'const char*'
52: error: initializing argument 1 of 'void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]'
Thank you so much everyone.
If it is applicable I am using XCode 3.2.6, and Mac OS X 10.6.8
Please don't ask me to upgrade or download anything, it is a school laptop, and I don't have sudo privileges.
If you know any scripting languages like Python or Perl, you should probably use those instead of C++ for what you're trying to do; they have much more intuitive facilities for what you want to do, and the syntax is much cleaner.
If you're gonna stick with C++, this is what you might consider;
Place every text file inside a folder (let's call it questions), and sets its filename to an integer (no extension).
Generate an integer randomly, possibly with a maximum value (depending on how you're numbering these questions).
If there exists a file in questions named for that integer (i.e. if you draw 41, then if ./questions/41 exists), use it. If not, draw again.
By the way, you wouldn't happen to go to high school on Long Island, would you? If so, I think we might have gone to the same school (though I graduated).

What am I doing Wrong with this C++ code?

Sorry, forgot the code
Here is the incorrect code.
I have been trying to get this working, but all the logical operators do not work.
#include <iostream>
#include <string>
using namespace std;
string repeat;
string repeatnum;
string prompt = "|-[]->";
int main()
{
string entry;
bool Running = true;
while(Running == true)
{
cout << "\n";
cout << prompt;
cin >> entry;
if(entry == "Exit") return 0;
if(entry == "Help") cout << "HELP:\nThsi is a simple program, try an input";
if(entry == "ChangePrompt")
{
cout << "What do you want to change the prompt to?: ";
cin >> prompt;
}
if(entry == "Repeat" || "repeat")
{
cout << "What string do you want to repeat?: ";
cin >> repeat;
cout << "How many times do you want to repeat" << repeat << "(1-9)?: ";
cin >> repeatnum;
if(repeatnum > 0){}
}
}
char f;
cin >> f;
return 0;
}
Here is the error I am getting.
Error:
C:\Users\Packard Bell\Desktop\test\main.cpp||In function 'int main()':|
C:\Users\Packard Bell\Desktop\test\main.cpp|29|error: no match for 'operator>' in 'repeatnum > 0'|
||=== Build finished: 1 errors, 0 warnings ===|
Because at line 29 in main.cpp you attempt to do repeatnum > 0 and repeatnum is a type with no overloaded operator >.
In addition to the repeatnum problem, this piece of code isn't doing what you want
if(entry == "Repeat" || "repeat")
It should be
if(entry == "Repeat" || entry == "repeat")
From the given info, I can only guess that the variable repeatnum is an object of a class or structure which you cannot use to directly compare it with 0. If the type of repeatnum is defined by you, add a member function that overloads operator > and handle it properly.
class YourType
{
// Class definition
public:
int operator >( int var )
{
// Code for comparison
// return result
}
};
Now after seeing the code. repeatnum is a string. You read input to the string and then compare it with integer. Now string does not have operator>-defined for integer so you need to convert the string to integer before comparison.
atoi(repeatnum.c_str());
Or use stringstream to do it.