C++ string input without newline in console - c++

As I wrote in the title, I would like to get a string input (with simple methods) without produce a newline in the console.
I searched in the web for more than an hour and couldn't find an answer to this simple question...why?
My program will be a simple Vocabulary trainer: I would like to write a French word and its translation in German into a text file. Therefore I first want to get the French word with
getline(cin, word_french);
Then I would like to print a " - " and after that I want to get the German word.
The problem is that after writing the French word, the "enter" will produce a newline in the console. So how not to get a newline after the string input?
I would like to appear it like this in the console:
(inserted french word) - (inserted german word)
string word_french, word_german;
cout<<"Beginn with the french word"<<endl;
ofstream out;
out.open("test.txt", ios::app);
std::cin.sync(); //clear buffer
getline(cin,word_french); //here the enter will produce the new line...
out<<"\n" +word_french;
cout<<" - ";
getline(cin, word_german);
out<<";"+word_german;
out.close();
Please try to keep it simple...

Related

Does `cin` produce a newline automatically?

Let's consider the following code:
#include<iostream>
int main()
{
std::cout<<"First-";
std::cout <<"-Second:";
int i;
std::cin>>i;
std::cout<<"Third in a new line.";
while(1){}
}
The output when value 4 is given to i is:
First--Second:4
Third in a newline
cout doesn't print any newline. But after I input any value(4) for i a newline is printed. There could be two possible reasons for this:
The Enter key I press after typing a numerical value for i is printed as a newline.
cin automatically generates a newline.
Although the first reason seems more reasonable but the reason, I am thinking 2nd reason could also be true, is because after Third is printed when I press Enter no new line is printed even the program continue to run because of while(1)--which means the console window doesn't print a newline when Enter key is pressed. So it seems like cin automatically prints a newline.
So, why is the newline being generated after I give input to cin? Does cin automatically prints a newline?
The number and newline you entered is printed by the console software. cin won't print anything in my understanding.
Try giving some input via redirect or pipe, and I guess you will see no new line printed.
For example:
$ echo 4 | ./a.out
First--Second:Third in a new line.
where $ is the prompt and echo 4 | ./a.out(Enter) is your input.
Check this out: http://ideone.com/tBj1uS
You can see there that input and output are separated.
stdin:
1
2
stdout:
First--Second:Third in a new line.
Which means, that the newline is produced by the Enter key and is a part of the input, not the output.
If someone will have the same problem, I was able to solve it like this:
string ans1;
getline(cin, ans1);
ans1.erase(remove(ans1.begin(), ans1.end(), '\n'),
ans1.end());
int ans1int = atoi(ans1.c_str());
Basically, it works by deleting all the newline characters in the string, and then ,aking it integer or whatever else you need. Also you will need algorithm library for it
It's not that elegant, but hey, it works!

sscanf input not working

I have tab seperated records like this
1000 Muhammad Aashir 0213-4211685 123456 0
first I have read the line by using fgets and now i am trying to extract contents by using sscanf, but there is an unexpected problem... please help I am beginner
here is the code
char buffer[SIZE];
Account req;
while(fgets(buffer,SIZE,fptr))
{
cout<<endl<<buffer<<endl;
sscanf(buffer,"%d\t%s\t%s\t%s\t%ld\n",&req.acc_num,req.name,req.mobileno,req.pass,&req.acc_bal);
cout<<endl<<req.pass;
}
output of BUFFER is same as the record line
but after extracting values, when I am displaying the 'req.pass' the value is incorrect
req.pass is displaying '0213-4211685' but it has to display '123456'
sscanf will capture until reaching any kind of whitespace. In your case, req.name only contains Muhammad. This will cause the rest of your variables to contain the wrong info.
If you need to use sscanf(), you'll have to replace instances of " " in your name with an escape character, like "_" for example.

Why must type getline(cin, string) twice?

need your help in getting user inputs.
I want users to type a string that has spaces.
i cant use cin>>variable as the space in between makes the problem go wrongly.
if i use getline(cin,string_variable) it works correctly. but i need to type twice in order to make it work proberly.
cout<<"Enter movie name";
getline(cin, mvName);
getline(cin, mvName);
Is there a better way to get user input than this or is there any other codes to type rather than typing the getline twice? Pls advice.
When switching between formatted input using in >> value and unformatted input, e.g., using std::getline(in, value) you need to make sure that you have consumed any whitespace you are not interest in. In you case there is probably a newline in the buffer from a prior input. Assuming you are nit interested in leading whitespace the easiest approach is to use something like this:
if (std::getline(std::cin >> std::ws, mvName)) {
process(mvName);
}
BTW, you should always check that your input was successful.
I had no issues using:
char mvName[32];
cin.getline(mvName, 32);
And I only had to call it once, again with no issues.
Maybe you just forget to add \n in your prompt message:
cout<<"Enter movie name:\n";
But if you want skip empty lines - do this:
// skip empty lines
while (cin >> mvName && mvName.empty());
// here mvName contains non empty string or it is empty because of error in reading
....
As the question contains no new-line character I suspect you hit enter to move down from the "Enter movie name" question? This would put a blank line into stdin, which the first getline() would read and then second getline() would read your entered text.
To remove the requirement of typing the initial new-line character just add it to the question's string literal:
std::cout<< "Enter movie name:\n";
cout<<"Enter movie name";
getline(cin, mvName);
Works fine!
Maybe you had to use getline(cin, mvName); twice was because you inputted some character into the first getline(cin, mvName); like Space, Enter, etc.

C++ Filter Content from Text File

I have been wanting to extract a line of text once [1],[2] ... [n] is found. But it seems like I couldn't get my thinking out to store a line into a char starting with [1].
void ExtractWebContent::filterContent(){
char str [10];
ifstream reading;
reading.open("file_Currency.txt");
while (!reading.eof()){
reading.get(str,10,'[1]');
cout << str << endl;
}
cout << str;
reading.close();
}
This is the file that I want to extract from..
CAPTION: Currencies
Name Price Change % Chg
[80]USD/SGD
1.2606 -0.00 -0.13%
USD/SGD [81]USDSGD=X
[82]EUR/SGD
1.5242 0.00 +0.11%
EUR/SGD [83]EURSGD=X
I am using linux, C++ programming. This is meant to filter figures obtained from HTML text file.
Any help would be very much appreciated. Thank you!
The big error you have is that you treat a single character as a string. The third argument is supposed to be a single character delimiter, i.e. a character that separates records in the file. If you add the compiler option -Wall when compiling you will get a warning about having more than one character in the single-character literal.
One way of doing what you want, is to use regular expressions.

Input filtering using scanf

I want to filter input. I don't know what is the best way. I want words starting with alpha-bates to be read. For example, if the input is:
This is 1 EXAMPLE1 input.
The string should be like this:
This is EXAMPLE1 input
What is the easiest way to filter input like this?
I tried using "%[a-zA-Z]s", but it not working.
Your scan string "%[a-zA-Z]s" probably isn't want you think it is. Drop that trailing s.
"%[a-zA-Z]" will scan a string consisting entirely of lower and uppercase letters. So numbers will be discounted. However, you want to scan alpha-numeric strings that begin with a lower or uppercase letter. scanf doesn't provide a facility to look for a string in that way. You can, instead, scan for an alpha-numeric string with "%[a-zA-Z0-9]", and then drop the scanned input if it the first character of the string is numeric.
Using scanf is tricky for various reasons. The string may be longer than you expect, and cause buffer overflow. If the input isn't in the format you expect, then scanf may fail to advance past the unexpected input. It is usually more reliable to read the input into a buffer unconditionally, and parse the buffer. For example:
const char *wants
= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
std::string word;
while (std::cin >> word) {
if (!isalpha(word[0])) continue;
std::string::size_type p = word.find_first_not_of(wants);
word = word.substr(0, p);
//... do something with word
}