tell cin to stop reading at newline - c++

Suppose I want to read line a of integers from input like this:
1 2 3 4 5\n
I want cin to stop at '\n' character but cin doesn't seem to recognize it.
Below is what I used.
vector<int> getclause() {
char c;
vector<int> cl;
while ( cin >> c && c!='\n') {
cl.push_back(c);
cin>>c;
}
return cl;
}
How should I modify this so that cin stop when it see the '\n' character?

Use getline and istringstream:
#include <sstream>
/*....*/
vector<int> getclause() {
char c;
vector<int> cl;
std::string line;
std::getline(cin, line);
std::istringstream iss(line);
while ( iss >> c) {
cl.push_back(c);
}
return cl;
}

You can read all whitespace by setting noskipws on the istream:
#include <ios>
#include <iostream>
#include <vector>
using std::vector;
vector<int> getc() {
char c;
vector<int> cl;
std::cin >> std::noskipws;
while (std::cin >> c && c != '\n') {
cl.push_back(c);
std::cin >> c;
}
return cl;
}
If the standard input contains only a single line, you might as well construct the vector with the istream_iterator:
#include <iostream>
#include <iterator>
#include <vector>
using std::vector;
vector<int> getc() {
// Replace char with int if you want to parse numbers instead of character codes
vector<int> cl{
std::istream_iterator<char>(std::cin),
std::istream_iterator<char>()
};
return cl;
}

You can use the getline method to first get the line, then use istringstream to get formatted input from the line.

Use std::getline, this will do the trick

getchar() is more efficient than cin when working with characters at this situation
I tried to do the same with a line of characters with unknown length and want it to stop at a newline but it has an infinite loop and haven't detect the newline, so I just used getchar() instead of cin and it works

From this link, it is quite simple to achieve this.
#include <stdio.h>
int main(void) {
int i=0,size,arr[10000];
char temp;
do{
scanf("%d%c", &arr[i], &temp);
i++;
} while(temp!= '\n');
size=i;
for(i=0;i<size;i++){
printf("%d ",arr[i]);
}
return 0;
}

Related

How to get input an array of strings with \n as delimiter?

#include<bits/stdc++.h>
using namespace std;
int main()
{
int i=0;
char a[100][100];
do {
cin>>a[i];
i++;
}while( strcmp(a[i],"\n") !=0 );
for(int j=0;j<i;i++)
{
cout<<a[i]<<endl;
}
return 0;
}
Here , i want to exit the do while loop as the users hits enter .But, the code doesn't come out of the loop..
The following reads one line and splits it on white-space. This code is not something one would normally expect a beginner to write from scratch. However, searching on Duckduckgo or Stackoverflow will reveal lots of variations on this theme. When progamming, know that you are probably not the first to need the functionality you seek. The engineering way is to find the best and learn from it. Study the code below. From one tiny example, you will learn about getline, string-streams, iterators, copy, back_inserter, and more. What a bargain!
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
int main() {
using namespace std;
vector<string> tokens;
{
string line;
getline(cin, line);
istringstream stream(line);
copy(istream_iterator<string>(stream),
istream_iterator<string>(),
back_inserter(tokens));
}
for (auto s : tokens) {
cout << s << '\n';
}
return 0;
}
First of all, we need to read the line until the '\n' character, which we can do with getline(). The extraction operator >> won't work here, since it will also stop reading input upon reaching a space. Once we get the whole line, we can put it into a stringstream and use cin >> str or getline(cin, str, ' ') to read the individual strings.
Another approach might be to take advantage of the fact that the extraction operator will leave the delimiter in the stream. We can then check if it's a '\n' with cin.peek().
Here's the code for the first approach:
#include <iostream> //include the standard library files individually
#include <vector> //#include <bits/stdc++.h> is terrible practice.
#include <sstream>
int main()
{
std::vector<std::string> words; //vector to store the strings
std::string line;
std::getline(std::cin, line); //get the whole line
std::stringstream ss(line); //create stringstream containing the line
std::string str;
while(std::getline(ss, str, ' ')) //loops until the input fails (when ss is empty)
{
words.push_back(str);
}
for(std::string &s : words)
{
std::cout << s << '\n';
}
}
And for the second approach:
#include <iostream> //include the standard library files individually
#include <vector> //#include <bits/stdc++.h> is terrible practice.
int main()
{
std::vector<std::string> words; //vector to store the strings
while(std::cin.peek() != '\n') //loop until next character to be read is '\n'
{
std::string str; //read a word
std::cin >> str;
words.push_back(str);
}
for(std::string &s : words)
{
std::cout << s << '\n';
}
}
You canuse getline to read ENTER, run on windows:
//#include<bits/stdc++.h>
#include <iostream>
#include <string> // for getline()
using namespace std;
int main()
{
int i = 0;
char a[100][100];
string temp;
do {
getline(std::cin, temp);
if (temp.empty())
break;
strcpy_s(a[i], temp.substr(0, 100).c_str());
} while (++i < 100);
for (int j = 0; j<i; j++)
{
cout << a[j] << endl;
}
return 0;
}
While each getline will got a whole line, like "hello world" will be read once, you can split it, just see this post.

terminate while loop using character

I need help with the following snippet:
Using string in the following loop terminates:
int main() {
string in;
while(1){
cin >> in;
if (in == "|")
break;
}
But using int in the following loop does not terminates:
int main() {
int in;
while(1){
cin >> in;
if (in == '|')
break;
else
cout<< in << "\n";
}
I want to terminate the last shown snippet. Is it possible to do using int in.
I've seen the post C++ Terminate loop using a char input to int but no solution.
While characters are represented in the computer as small integers, an int is not the same as a char. Not in C++.
When you read into an int variable the >> operator tries to parse the input as an integer, as a number and not as a character.
If you want to read a character then read a character:
char in;
std::cin >> in;
If you try to read an integer, and the input is not a number, then the input operator will fail. See e.g. this very simple example.
This is the approach I used
I needed to input integers to a vector as input using while loop indefinitely and terminate it using a character.
This approach takes the input as character and then convert this char into integer.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
char in;
std::vector<int> vec;
while(1){
cin>>in;
if(in == '|'){
break;
}
vec.push_back(in - '0');
}
for(int j=0; j<vec.size(); j++){
cout<<vec[j];}
return 0;
}

C++ Using std::getline in place of cin >>

In a problem were i have to take n number of strings as input and count the ones containing a given substring(case insensitive).
Here's my code:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include<string>
using namespace std;
int main()
{
std::string str2 = "hello";
std::string str3 = "HELLO";
short int n,count=0,i;
cin>>n;
std::string str1[n];
for(i=0;i<n;i++)
{
std::getline(std::cin,str1[i]); //here getline is taking only n-1 inputs
std::size_t found1=str1[i].find(str2);
std::size_t found2=str1[i].find(str3);
if(found1!=std::string::npos || found2!=std::string::npos)
count++;
}
cout<<count;
return 0;
}
Since i cant use cin as string includes spaces or cin.getline() as have to use string type in place of char[].
Problem with my code is std::getline() is only taking n-1 inputs.Cant figure out why?
The first getline after cin reads the remainder of the line, which is probably empty. This is why when reading user input, it is usually better to use getline and process input using code.
After cin >> n the input stream is positioned just after the number n. You can use a getline just to read the newline and then throw it away to position to the start of the next line.
This code should work
#include <iostream>
#include <string>
using namespace std;
int main() {
int n = 0, count = 0;
cin >> n;
do {
string str;
getline(cin, str);
if (str.find("HELLO") != string::npos || str.find("hello") != string::npos) {
count++;
}
} while (n-- && n >= 0);
cout << count << endl;
return 0;
}

taking strings with whitespaces in c++

#include<iostream>
using namespace std;
int main()
{
string p;
int n,i;
cin>>n;
for(i=1;i<=n;i++)
{
cin>>p;
cout<<p<<"\n";
}
return 0;
}
hiii..
i wanna take two strings and then print them one by one as in prog. but when i take n=2 and input the string "I wanna go"
it gives the output :
i
wanna
and it didn't ask me for second string.it is taking the string until it gets a whitespace.what should i do to resolve this?
You have to change the initial value of your iteration variable i in you for statement to the following one:
for(i=0;i<=n;i++)
Consider using std::getline.
std::string name;
std::getline(std::cin, name);
The above example is summarized from:
std::cin input with spaces?
Instead of operator >> you should use function std::getline. For example
#include <iostream>
#include <limits>
int main()
{
int n;
std::cin >> n;
std::cin.ignore( std::numeric_limits<std::streamsize>::max() );
// or simply std::cin.ignore();
for ( int i = 1; i <= n; i++ )
{
std::string p;
std::getline( std::cin, p );
std::cout << p << "\n";
}
return 0;
}

Transformation to lower case in C++

#include<iostream>
#include<string>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include <string>
#include <algorithm>
using namespace std;
string A,B;
int main()
{
int t,l,i;
scanf("%d",&t);
while(t--)
{
std::string str;
std::getline(cin, str);
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
cout<<str;
/*for(i=0;i<s.length();i++)
{
s[i]=toupper(s[i]);
}*/
}
return 0;
}
i wrote this code to convert to lower case but when run on ideone with input
1
hola please!!!
it shows output no can u tell or correct it morever this will help me learn the use of std:lowercase function taking getline cin as input rather than considering it as array
The problem is definitely with the way you are reading in. scanf("%d",&t); doesn't consume the return character, so it is still there on the getline, which will get an empty sting. Change it to scanf("%d\r",&t).
If you simplify the code, the problem can be reduced to:
int main() {
int t;
scanf("%d",&t);
std::string str;
std::getline(cin, str);
std::cout<<str;
}
This is because scanf reads from the input until it reaches a character that doesn't match, and it leaves that character in the input buffer. You input is "1\nhola please!\n\0", so scanf reads the 1, and leaves the rest: "\nhola please!\n\0". Then, you tell it to read until the next \n is found, which is immediately, so it returns an empty string.
The solution is: after using std::cin >> or scanf or whatever, if the next thing you want to do is read the rest of the line, you want to ignore that leading newline character. The C++ way to do this is std::cin.ignore(0xFFFFFFFF,'\n');, which will ignore the rest of the line. Alternatively, use scanf("%d\n" &t); to get the scanf to read in the newline character.
Related, you never check the validity of any of your input:
int main() {
int num_lines=0; //variables on different lines and initialized
std::cin >> num_lines
if (!std::cin)
return 1;
std::string str;
for(int j=0; j<num_lines && std::getline(sd::cin, str); ++j) {
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
std::cout << str;
}
return 0;
}
Or simply use < boost/algorithm/string.hpp > header and function boost::to_lower().
int t = 0;
scanf("%d",&t);
std::cin.ignore();
while(t--) {
std::string str;
std::getline(cin, str);
boost::to_lower(str);
std::cout << str << std::endl;
}