c++ cannot print escape character - c++

I am trying to write a program that interacts with some instruments that require commands beginning with the escape character (ascii 27) but am having trouble testing as the program seems to hang the moment it attempts to print the escape character. This program is compiled with g++ in an Ubuntu machine and run from gnome-terminal:
#include <cstdlib>
#include <iostream>
#include <unistd.h>
#include <limits>
using namespace std;
int main()
{
string str;
const int numSamples=10;
const int escapeInt = 27;
const char escapeChar = escapeInt;
// sleep(30);
//Ask for the latest test results
cin.clear();
// cin.ignore(numeric_limits<streamsize>::max());
cout << "\n\n\n";
cout << escapeChar << "PF2 -" << numSamples;
cerr << "\n\n\n" << escapeChar << "PF2 -" << numSamples;
// cin.ignore(2,'\n');
getline( cin, str, '\n');
cerr << str;
int k=1;
while (k<=numSamples)//getline(cin, str))
{
getline( cin, str, '\n');
k++;
cerr << str << endl;
}
return 0;
}
The output is just three blank lines and then the program becomes unresponsive. It doesn't even respond to ctrl-c. Any suggestions as to how to get around this?

Oh, I can answer my own question. As was suggested by #Alf, (Thank you) it seems that I just shouldn't be trying to print the escape sequence to cerr as that winds up being interpreted by my terminal which, in my case with gnome-terminal, is a no-no.
Thanks for the useful insight folks!

Related

First character of cstring removed during ifstream c++

The first character of cstring keeps being removed upon the second execution of getline in ifstream:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
char input[102];
ifstream keyTextFile("key.txt");
while (keyTextFile.getline(input, 102, '\n')) {
cout << input[0] << input[1] << endl;
cout << input << endl;
}
cout << input[0] << input[1] << endl;
keyTextFile.close();
return 0;
}
Currently, key.txt is one line:
0x0ffa331cc8765ddd
The code outputs:
0x
0x0ffa331cc8765ddd
x
The debugger shows input[0] changing from '0' to '\0' on the second execution of getline. How can I avoid this while allowing getline to scan a potentially large document?
please keep the answer to c-string implementation.

Using std::getline() to read a single line?

My goal is to prompt user to enter a message / sentence and then print it out on the screen, using getline(). The following is two different attempts I have tried out.
First Attempt:
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
int main(){
chat message[80];
cout << "\n what is your message today?" << endl;
cin.getline( message, 80); // Enter a line with a max of 79 characters.
if( strlen( message) > 0) // If string length is longer than 0.
{
for( int i=0; message[i] != '\0'; ++i)
cout << message[i] << ' ';
cout << endl;
}
}
Second Attempt:
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
int main(){
string a = "a string";
cout << "\n what is your message today?" << endl;
while(getline(cin,a))
cout << a;
cout<<endl
}
}
For the fist attempt, the code simply print out "what is your message today?" and quit. I do not have a chance to enter any string at all. For the second attempt, it keeps asking me enter the message. Each time, when I enter something with the "\n", it would display what I entered on the screen. I use control + c to interrupt the running process to make it stop.
EDIT: To clarify and explain on my side, I extract the first attempt from a longer code, which is as the following.
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
char header[] = "\n *** C Strings ***\n\n"; // define a c string
int main()
{
char hello[30] = "Hello ", name[20], message[80]; // define a c string hello, declare two other c strings name and message
string a="fivelength";
cout << header << "Your first name: ";
cin >> setw(20) >> name; // Enter a word.
strcat( hello, name); // Append the name.
cout << hello << endl;
cin.sync(); // No previous input.
cout << "\nWhat is the message for today?"
<< endl;
cin.getline( message, 80); // Enter a line with a max of 79 characters.
if( strlen( message) > 0) // If string length is longer than 0.
{
for( int i=0; message[i] != '\0'; ++i)
cout << message[i] << ' ';
cout << endl;
}
return 0;
}
For the above code, it does not give me a chance to enter a message on the screen. I will put it as another question.
You are overcomplicating this, you can simply use std::string, which is the de-facto C++ string, and call the method, without using a loop.
You don't need a loop, since you are not going to repeatedly read lines, but only want to read one line, so no loop is needed.
#include <iostream>
#include <string> // not cstring, which is the C string library
using namespace std;
int main(void)
{
string message; // it can be an empty string, no need to initialize it
cout << "What is your message today?" << endl;
getline(cin, message);
cout << message;
cout<<endl;
return 0;
}
Output (Input: "Hello Stack Overflow!"):
What is your message today?
Message: Hello Stack Overflow!
PS: As #fredLarson commented, if you change chat to char in your first example, it should work. However, that code has a lot of commonalities with C.

Issue printing .txt file in program C++

I have a program that takes a text file and list the words and how many times they are used. It works but I can't figure out how to print out the text file. Above the sorted words and how many times they appear, I want to display the text from the file. How would I do that? I tried several things but it either does nothing or screws up the rest of the code saying there are 0 unique words. And lastly how would print out the results so they are more ... table -ish...
/*
Something like this:
Word: [equal spaces] Count:
ask [equal spaces] 5
anger [equal spaces] 3
*/
Thank you for any assistance you can provide me.
#include <iterator>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <cctype>
using namespace std;
string getNextToken(istream &in) {
char c;
string ans="";
c=in.get();
while(!isalpha(c) && !in.eof())//cleaning non letter charachters
{
c=in.get();
}
while(isalpha(c))
{
ans.push_back(tolower(c));
c=in.get();
}
return ans;
}
string ask(string msg) {
string ans;
cout << msg;
getline(cin, ans);
return ans;
}
int main() {
map<string,int> words;
ifstream fin( ask("Enter file name: ").c_str() ); //open an input stream
if( fin.fail() ) {
cerr << "An error occurred trying to open a stream to the file!\n";
return 1;
}
string s;
string empty ="";
while((s=getNextToken(fin))!=empty )
++words[s];
while(fin.good())
cout << (char)fin.get(); // I am not sure where to put this. Or if it is correct
cout << "" << endl;
cout << "There are " << words.size() << " unique words in the above text." << endl;
cout << "----------------------------------------------------------------" << endl;
cout << " " << endl;
for(map<string,int>::iterator iter = words.begin(); iter!=words.end(); ++iter)
cout<<iter->first<<' '<<iter->second<<endl;
return 0;
}
I would just use a simple for loop like this:
for (int x = 0; x < words.size(); x++){
cout >> words[x] << endl
}
And then modify from there to get your desired format.
I did notice though, that you are not returning a value for main in all paths of the above code, which should give a compile time error, but did not when I compiled it, for some reason. I would remind you that you need to have a return value for main. Unless I am misunderstanding your question. I could not run this program without creating a sample file, and so could not test it without extra work. But the program did compile. I did not expect to, because of the missing return statement. If you can make this reproduce your error without me having to create a sample file of words, ei insert the list of words into the code and minimally reproduce the error, I would be able to help you better. As it is, I hope that I helped you.
Something like this should make it:
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <string>
int main( int argc, char* argv[] )
{
std::string file;
std::cout << "Enter file name: ";
std::cin >> file;
std::fstream in( file.c_str() );
if ( in.good() )
{
std::unordered_map<std::string, int> words;
std::string word;
//Use this to separate your words it could be '\n' or anything else
char cSeparator = ' ';
while ( in >> word )
{
//Print the word
std::cout << word << cSeparator;
++words[word];
}
std::cout << std::endl;
//Headers Word and Count separated by 2 tabs
std::cout << "Word:\t\tCount:" << std::endl;
for ( auto& w : words )
std::cout << w.first << "\t\t" << w.second << std::endl;
}
in.close();
return EXIT_SUCCESS;
}
However this is assuming that the text file only contains the words, if you have other kind of stuff there, you should be able to filter it as you want.

Password function and arrays

I'm writing a simple password program, but the else if statement always applies, even if the password is put in correctly. This works fine if I use a single char instead of an array, and change "hotdog" to 'h', and I think it might have something to do with unseen characters, like a space or return. I was sure cin.ignore() took care of return/enter.
Sorry, I'm fairly new to programming.
#include <iostream>
int main()
{
std::cout << "What is the password?\n" << std::endl;
char password[20] = "NULL";
std::cin >> password;
std::cin.ignore();
std::cout << password << " is your entry?\n";
if (password == "hotdog")
{
std::cout << "Correct!";
}
else if (password != "hotdog")
{
std::cout << "Incorrect!";
}
else
{
}
std::cin.get();
}
Firstly, change char password[20] to string password. This prevents a buffer overflow if they type in more than 20, and it enables you to use == for string comparison.
The code std::cin.ignore() ignores a single character. You want to actually ignore the entire remainder of the line. There is no way to ignore "everything else typed so far" because there may have been characters typed which are still buffered. In practice, it works well to treat input as a series of lines.
The most accurate way to ignore the rest of the line is to ignore all characters up to and including '\n', which appears in the input stream at the end of the line (by definition).
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
which may require #include <limits>. Another way is to read a string and discard it:
std::string t;
std::getline( std::cin, t );
NB. Check your understand of if...else . Once you have if ( condition ), then the next else will already get everything that was not in that condition. It's pointless to actually write else if ( !condition ); and your final else { block can never be entered, because the previous two conditions were exhaustive.
The problem is with how you are using the if-else statement. Try this code out:
#include <iostream>
int main()
{
std::cout << "What is the password?\n" << std::endl;
char password[20] = "NULL";
std::cin >> password;
std::cin.ignore();
std::cout << password << " is your entry?\n";
if (stricmp("hotdog", password) == 0)
{
std::cout << "Correct!";
}
else
{
std::cout << "Incorrect!";
}
std::cin.get();
}
When I take your code and compile it, even the term hotdog does not work properly, I obtain the following:
What is the password?
hotdog
hotdog is your entry?
Incorrect!
As suggested above, a string is a better method and works as intended based on your requirements. Here is sample replacement code that works as intended (with this code spaces are allowed, with the other answers, spaces are not, it all depends what is intended):
#include <iostream>
#include <string>
using namespace std;
int main (int argc, char ** argv)
{
cout << "What is the password?\n" << endl;
string password = "NULL";
getline(cin, password);
cout << password.c_str() << " is your entry?\n";
if (password == "hotdog")
{
cout << "Correct!";
}
else if (password != "hotdog")
{
cout << "Incorrect!";
}
else
{
// Added from original; however, this should never occur
cout << "Else?";
}
system("pause");
return 0;
}
Output of Replacement Code
What is the password?
hotdog
hotdog is your entry?
Correct!
You had to use strcmp() function to compare strings properly in c++,so I added the cstring library:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main(){
string password;
cin >> password;
cout << password << " is your entry?\n";
char hd [7] = "hotdog";
if (strcmp(password.c_str(),hd) == 0){
cout << "Correct!\n";
}
else if (strcmp(password.c_str(),hd) != 0){
cout << "Incorrect!\n";
}
else{
cin.get();
}
}

Cout doesn't print on display (console)

so i have a code that's supposed to find a string of characters in a certain .txt file, if the input is in the file, it says "yey i found it" but when it isnt, its supposed to say "didnt find anything", but it just skips that step and ends.
I'm a beginner so sorry for any obvious mistakes.
#include <stdio.h>
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void)
{
setlocale(LC_ALL, "");
string hledat;
int offset;
string line;
ifstream Myfile;
cout.flush();
cout << "Welcome, insert the string to find in the file. \n \n \n" << endl;
cin.get();
cout.flush();
Myfile.open("db.txt");
cin >> hledat;
if (Myfile.is_open())
{
while (!Myfile.eof())
{
getline(Myfile, line);
if ((offset = line.find(hledat, 0)) != string::npos)
{
cout.flush();
cout << "Found it ! your input was : " << hledat << endl;
}
}
Myfile.close();
}
else
{
cout.flush();
cout << "Sorry, couldnt find anything. Your input was " << hledat << endl;
}
getchar();
system("PAUSE");
return 0;
}
There are three possible cases.
The file was not successfully opened.
The file was successfully opened, but the string was not found.
The file was successfully opened, and the string was found.
You have a printout for cases 1 and 3, but not 2.
By the way, your loop condition is wrong. Use the result of the call to getline, which is the ostream object itself after the read attempt.
while (getline(MyFile, line))
{
...
}
The loop will terminate upon an unsuccessful read attempt, which will happen after you read the last line. The way you have it, you will try to read after the last line, which will be unsuccessful, but you will still try to process that non-existent line because you don't check eof until the loop starts over.
Just comment out //cin.get(); , you dont need it.
Output:
Welcome, insert the string to find in the file.
apple
Found it ! your input was : apple
Other than that, it works like a charm.
Corrected code:
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void)
{
setlocale(LC_ALL, "");
string hledat;
int offset;
string line;
ifstream Myfile;
cout.flush();
cout << "Welcome, insert the string to find in the file. \n \n \n" << endl;
//cin.get(); <----- corrected code
cout.flush();
Myfile.open("db.txt");
cin >> hledat;
if (Myfile.is_open())
{
while (!Myfile.eof())
{
getline(Myfile, line);
if ((offset = line.find(hledat, 0)) != string::npos)
{
cout.flush();
cout << "Found it ! your input was : " << hledat << endl;
}
}
Myfile.close();
}
else
{
cout.flush();
cout << "Sorry, couldnt find anything. Your input was " << hledat << endl;
}
getchar();
system("PAUSE");
return 0;
}