In my program it should be an option to ask a user for input, and then save input string into the file. My problem is, - when I put cin in any of it forms, inside Switch, program will stuck circling indefinitely, right after i press enter after finish typing new text. What could cause the problem?
#include <iostream>
#include <fstream>
#include <iterator>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <algorithm>
#include <chrono>
#include <random>
#include <vector>
using namespace std;
void changePlainText()
{
ofstream nFile("plaintext.txt");
string newText;
cout << "Enter new plain text" << endl;
getline(cin, newText);
nFile << newText;
nFile.close();
}
int main()
{
int uInput = 0;
do
{
printf("2.Change content of the plain text file: \n");
cin >> uInput;
switch (uInput)
{
case 1:
break;
case 2:
changePlainText();
break;
}
} while (uInput != 5);
cout << "Closing program" << endl;
system("pause");
}
After I type something in console and press enter, the program enters never ending circle. It still stuck even if I just write simple cin >> i, in switch case.
Take a look at this question. I debugged your code and I experienced that exact behavior. The accepted answer explains quite well what's happening and also provides a solution.
I tried with boost, I changed
cin >> uInput;
to
string inputString; // so you know what inputString is
getline(cin, inputString);
uInput = boost::lexical_cast<int>(line);
and it's working fine now.
Related
I'm working on a project and I need to select a different .txt every time based on the input.
This is what I have:
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <fstream>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
string hp, att, def, vel, spec;
string answer, monster;
do
{
cout << "Which Monster?: ";
cin >> monster;
cout << endl;
ifstream selection;
selection.open(monster+".txt");
selection.close();
cout << endl << "Again? ";
cin >> answer;
}
while (answer == "y");
cout << "Hello world!" << endl;
return 0;
}
I have to get the monster string and search the .txt with the same name.
If I type "Troll" it will search for the Troll.txt
Is there a way?
This is the error I get:
F:\GdR\Campagna 1\CalcoloStats\main.cpp|22|error: no matching function for call to 'std::basic_ifstream::open(std::__cxx11::basic_string)'|
Given that monster is a std::string, this expression:
monster + ".txt"
is also a std::string.
Since C++11, you can use this as an argument to ifstream's open function just fine. However, until then, you are stuck with a limitation of ifstream which is that it can only take a C-style string.
Fortunately, you can get a C-style string from a std::string using the c_str() member function.
So, either:
selection.open((monster + "txt").c_str());
Or get a modern compiler / switch out of legacy mode.
Thanks Lightness Races in Orbit, solved with C++11 Compiler flag
I want the user to enter the name of a file, and if the file exists, print out all the contents of the file.
At the moment the uncommented code, takes a name of a file that the user inputs, for example. example.txt and prints out most (not the last word?) of the file. I've tried to implement this instead by using string (commented code is attempt) but clearly its incorrect.
I also wondering if i can automatically add .txt to the end of the user input, so that the console could ask - "which subject should we find more information on" user inputs "math" and it will open "math.txt"
Here is what I´ve tried:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main() {
char filename[50];
//string getcontent;
ifstream name;
cin.getline(filename, 50);
name.open(filename);
if (!name.is_open()) {
exit(EXIT_FAILURE);
}
char word[50];
name >> word;
while (name.good()) {
cout << word << " ";
name >> word;
}
//if (!name.is_open()) {
//while (! filename).eof())
//{
//getline(name, getcontent)
//cout << getcontent << endl;
//}
//exit(EXIT_FAILURE); //comes from cstdlib
//}
//}
system("pause");
return 0;
}
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main() {
string filename;
string getcontent;
ifstream name;
cin >> filename;
filename.append(".txt"); // add extension.
name.open(filename);
if (!name.is_open()) {
exit(EXIT_FAILURE);
}
while (true)
{
getline(name, getcontent);
if (name.eof()) break;
cout << getcontent << endl;
}
return 0;
}
I found this and it helped me with a somewhat different problem and I also thought that I might be able to help. This is coded in windows. (I'm a beginner so forgive me if I made some obvious mistakes)
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
ifstream fin;
int main()
{
//char filename[50],word[50];
string filename,word;
//cin.getline(filename,50);
getline(cin,filename);
//strcat(filename,".txt");
filename.append(".txt");
fin.open(filename);
if(fin.is_open())
while(fin>>word)
cout<<word<<endl;
else
cout<<"No such file"<<endl;
return 0;
}
So i got a little beginner problem here.
I cant seem to print out a string with char and integers in it.
#include <iostream.h>
#include <conio.h>
Main()
{
Char date[20];
Clrscr();
Cout<<"enter date: ";
Cin>>date;
Cout<<endl;
Cout<<date;
Getch();
Return 0;
}
My input here is suppose to be :
January 1-5,1999
But all it shows is :
January.**
Use getline(). Otherwise it cuts it after a space. Also, do not use capitals for cout, etc.
Like
string date;
getline(cin,date, '\n');
The answer by #Caspar Wylie is correct but if are using a very old/outdated compiler(guessed from conio.h and iostream.h header files) then try this
#include <iostream.h>
#include <conio.h>
int main()
{
char date[20];
cin.getline(str,20);
cout << date << endl;
getch();
return 0;
}
I am working on a console program for Windows, and one of my settings is an option to change the console and text color.
I am using c++, so I can do something like system("color 07");, which will make the background black and the text white.
What I want to do is to present all 16 color options, and then let the user take his pick.
(Below is a portion of my code):
int a;
int b;
cout << "Please enter your background color." << endl;
cin >> a; //the user inputs 0
cout << "Please enter your text color." << endl;
cin >> b; //the user inputs 7
How to I pass the two variables to the system() call? I googled around, but all I could find were string to system(), which I do not want.
Also, I am very well aware of how evil system() is, so if anyone has other options other than system() that will do the same thing, that would be fine. But please do not tell me how evil system() is.
Thanks in advance!!
The system command takes a single const char* parameter. Therefore you just need to build a string for the command you wish to execute.
#include <iostream>
#include <sstream>
#include <string>
int main()
{
int backgroundColor;
std::cout << "Enter background color\n";
std::cin >> backgroundColor;
int foregroundColor;
std::cout << "Enter foreground color\n";
std::cin >> foregroundColor;
std::stringstream stream;
stream << "color " << backgroundColor << foregroundColor;
std::cout << "Command to execute: '" << stream.str() << "'\n";
::system(stream.str().c_str());
return 0;
}
This could be a simpler solution using C++ constructs.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
string bgClr,fgClr;
cin >> bgClr >> fgClr;
::system((bgClr+fgClr).c_str());
return EXIT_SUCCESS;
}
char command[500] = "";
sprintf(command, "color(%d, %d)", a, b);
int result = system(command);
Which command lets me to cout my new random numbers by presing enter? I tried to write system("pause") but then comes line "press any key to continue" which I dont like. Is there any possibility to just press enter button and see numbers one after one?
Here's the program code:
#include <iostream>
using namespace std;
#include <stdlib.h>
#include <ctime>
int main()
{
int i, k;
srand(time(0));
for (i = 0; i < 20; i++)
{
cout << (rand() % 8) << endl;
}
}
#include <limits>
// ...
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
The advantage over reading a single character is that this will make sure that no stray characters are left over into the buffer.
Here is a slightly more modern C++ take on it:
#include <iostream>
#include <ctime>
#include <random>
int main()
{
std::mt19937 rng(std::time(0));
std::uniform_int_distribution<int> gen(0,7);
for (int i=0;i<20;i++)
{
std::cout << gen(rng);
std::string line;
std::getline(std::cin, line);
};
}
You can simply use getchar() which will read one keypress and then continue. If you want to specifically break on the enter key, use something like while (getchar() != "\n");
add cin >> SomeVariableThatCouldAcceptAnythingInCaseYouPressSomethingElseBeforeTheEnterKey either before or after the cout, whichever you like.
Just read a string, right?
#include <string>
....
for (i=0;i<20;i++)
{
std::string str;
cin >> str; // this should pause until the user presses enter
cout << (rand()%8) << endl;
};
What about a simple cin.get()? No need for any temporary variable nor any C functions.