When I enter "1", for loop should run one time. but it just prints "0". I don't know why.
I think the problem is with "getline(cin, input)" but i dont know the problem.
Here is the code:
int main()
{
string input;
int t, output, occured_length, lenght, match;
char occured[26];
cin>>t;
for(int i=0; i<t; i++) //I am talking about this loop
{
occured_length = 0;
getline(cin, input); //This might be causing the problem
lenght = input.size();
for(int j=0; j<lenght; j++)
{
if(occured_length == 25)
{
cout<<"\n"<<occured_length+1;
break;
}
match = 0;
for(int k=0; k<occured_length; k++)
{
if(input[j] == occured[k])
{
match= 1;
break;
}
}
if(match == 0)
{
occured_length++;
occured[occured_length] = input[i];
}
}
cout<<"\n"<<occured_length;
}
return 0;
}
input is empty & length is 0
istream& getline (istream& is, string& str);
Gets line from input stream into string. It extracts characters from is and stores them into str until the the newline character, '\n' is found.
\n remains in the input stream, you need to another dummy input reading, otherwise you will get input = "" on next getline
cin>>t;
char c;
cin >> c;
The problem is that after the input with using operator >>
cin>>t;
the input buffer will contain new line character. And next statement with getline
getline(cin, input);
reads an empty string.
You have to remove the new line character from the input buffer usig method ignore. For example
#include <limits>
//...
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
The call of ignore should be before getline and after operator >>.
Related
This code is giving output YES just after entering the value of test case.
Code: for alphanumeric pallindrome
int main() {
int t;
cin>>t;
while(t--){
string s;
int count = 0,size = 0;
getline(cin,s);
cout<<s<<endl;
s.erase(remove_if(s.begin(),s.end(),not1(ptr_fun((int(*)(int))isalnum))), s.end());
for(int i=0;i<=s.size()/2;i++){
size++;
if(tolower(s[i])==tolower(s[s.size()-i-1])){
count++;
}
else
break;
}
if (count==size)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}
Output I am getting is YES without giving any input of string
For Input:
2
I am :IronnorI Ma, i
Ab?/Ba
Your Output is:
YES
I am :IronnorI Ma, i
YES
This code is giving output YES just after entering the value of test
case. Output I am getting is YES without giving any input of string
Your problem is here:
/* code */
cin>>t; -----------> std::cin
while(t--)
{
string s;
int count = 0,size = 0;
getline(cin,s); ------------> std::getline()
/* remaining code */
Reading with something like std::cin leaves the newline in the input stream. When the flow of control reaches std::getline(), the newline will be discarded, but the input will cease immediately. This leads, std::getline()s attempt read a new line and skips the input.
FIX: When switching from white space delimited to newline delimited input, you want to clean all newlines from the input stream by doing a std::cin.ignore()
The fixed code should be: https://www.ideone.com/ucDa7i#stdin
#include <iostream>
#include <string>
#include <limits>
#include <algorithm>
int main()
{
int t;
std::cin >> t;
// fix
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
while(t--)
{
std::string s;
int count = 0,size = 0;
getline(std::cin,s);
/* remaining code */
}
I am trying to get input data from a txt file on Linux / Mint. So, after compiling the code I run the following command: ./a.out output.txt
I need to fill a two-dimensional array but like a jagged array (the number of columns in each row is different). So I want to split it by looking character what is read from file. If the character is '\ n', I want to fill the second line. But I guess I can not read the '\ n' character. I hope I can explain the problem.
I'm writing the code, maybe it will be more clearer.
my input.txt file is:
my c++ code part is for getting input:
for (int i = 0; i<n; i++) {
char ch;
cin >> ch;
int j = 0;
while (ch != '\n') {
arr[i][j] = ch;
cin >> ch;
j++;
}
}
I want to that, if the character is equals the '\n' then program goes on to fill the array to next row.
arr[0][0] = 'a';
arr[0][1] = 'f'
arr[0][2] = 'h'
arr[1][0] = 'b'
arr[1][1] = 'e'
arr[1][2] = 'g'
arr[2][0] = 'c' .......)
When you do cin >> ch it will skip whitespace, which includes spaces, tabs and newline characters. Perhaps, you need to read entire lines using std::getline, and then process each line separately.
For example:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
char ch;
std::string line;
int ln = 0;
while (getline(cin, line)) // read entire line
{
istringstream is;
is.str(line);
while (is >> ch) // now read individual chars from that line
cout << "line: " << ln << " char: " << ch << endl;
ln++;
}
}
And your loop should be something like this:
std::string line;
for (int i=0; i<n; ++i)
{
char ch;
if (!std::getline(cin, line))
break;
std::istringstream is;
is.str(line);
for (int j=0; is >> ch; ++j)
arr[i][j] = ch;
}
You omitted details on how you declare your arr, but it doesn't seem like the code you've shown would handle it properly. Perhaps, it would be better to use vectors:
std::vector<std::vector<char> > arr;
std::string line;
char ch;
while (std::getline(cin, line)) // cin should probably be replaced with ifstream
{
std::istringstream is;
is.str(line);
arr.push_back(vector<char>());
for (int j=0; is >> ch; ++j)
arr.back().push_back(ch);
}
#include <iostream>
using namespace std;
int main()
{
int n,t=0,k=0;
cin>>n;
char data[n][100];
int num[n];
for(int i=0;i<n;i++)
{
while(1)
{
cin>>data[i][t];
cout<<data[i][t]<<endl;
if(data[i][t]=='\n') break;
k++;
if(k%2==1) t++;
}
cout<<i;
num[i]=(t-2)/2;
k=0;
t=0;
}
for(int i=0;i<n;i++)
{
while(1)
{
cout<<data[i][t];
if(t==num[i]) break;
t++;
}
t=0;
}
}
here is the code I have written in c++ which gives the even numbered characters from the starting half of every word given by the user but when giving input after pressing enter the loop should break but the loop is not breaking
while(1)
{
cin>>data[i][t];
cout<<data[i][t]<<endl;
if(data[i][t]=='\n') break;
k++;
if(k%2==1) t++;
}
By default formatted input using the "input" operators >> skip white-space, and newline is a white-space character. So what's happening is that the >> operator simply waits for some non-white-space input to be entered.
To tell the input to not skip white-space you have to use the std::noskipws manipulator:
cin>>noskipws>>data[i][t];
There are some ways to implement in C++ what OP is trying to do. I'd start avoiding Variable Length Arrays, which aren't in the Standard and using std::strings and std::vectors instead.
One option is to read an entire line from input with std::getline and then process the resulting string to keep only the first half of even chars:
#include <iostream>
#include <string>
#include <vector>
int main() {
using std::cin;
using std::cout;
using std::string;
cout << "How many lines?\n";
int n;
cin >> n;
std::vector<string> half_words;
string line;
while ( n > 0 && std::getline(cin, line) ) {
if ( line.empty() ) // skip empty lines and trailing newlines
continue;
string word;
auto length = line.length() / 2;
for ( string::size_type i = 1; i < length; i += 2 ) {
word += line[i];
}
half_words.push_back(word);
--n;
}
cout << "\nShrinked words:\n\n";
for ( const auto &s : half_words ) {
cout << s << '\n';
}
return 0;
}
Another is, as Joachim Pileborg did in his answer, to disable skipping of leading whitespaces by the formatted input functions with std::noskipws manipolator and then read a char at a time:
// ...
// disables skipping of whitespace and then consume the trailing newline
char odd, even;
cin >> std::noskipws >> odd;
std::vector<string> half_words;
while ( n > 0 ) {
string word;
// read every character in a row till a newline, but store in a string
// only the even ones
while ( cin >> odd && odd != '\n'
&& cin >> even && even != '\n' ) {
word += even;
}
// add the shrinked line to the vector of strings
auto half = word.length() / 2;
half_words.emplace_back(word.begin(), word.begin() + half);
--n;
}
// ...
I am using getline and ignore but something is not working properly,
Below is the sample code which am not able to understand how it is working.
int main()
{
string str;
int t,length;
cin>>t; // t is the number of test cases
while(t--!=0)
{
cin.ignore();
getline(cin,str);
length=str.size();
cout<<"length="<<length;
}
}
Sample output:
2
hey hi
length 6
hey hi
length 5
Why is the length decreasing? Is this because of getline and ignore function? Any help would be appreciated.
The reason it is giving a different length is becaus your ignore() function ignores only one character. The first time round it ignores the return key you pressed after entering the number. But std::getline() deletes the return character for you. So the second time round ignore() deletes the first letter of your string making it "eh hi".
int main()
{
string str;
int t, length;
cin >> t; // does not remove the RETURN character
while(t-- != 0)
{
// first removed RETURN character after removes first letter
cin.ignore();
getline(cin, str);
length = str.size();
cout << "length = " << length;
}
}
Try using this instead:
int main()
{
string str;
int t, length;
cin >> t; // does not remove the RETURN character
while(t-- != 0)
{
// cin.ignore(); // dont do this here please
// cin >> ws skips all whitespace characters
// including the return character
getline(cin >> ws, str);
length = str.size();
cout << " length = " << length;
}
}
Alternatively (maybe better) you can move the ignore() function out of the loop to where t is really needed:
#include <limits>
int main()
{
string str;
int t, length;
cin >> t; // does not remove the RETURN character
// ignore as many characters as necessary including the return
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
while(t-- != 0)
{
// cin.ignore(); // not here
getline(cin, str);
length = str.size();
cout << " length = " << length;
}
}
The cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); looks complicated but it is the only way to guarantee that any spurious characters (like spaces) are removed. You can probably get away with just cin.ignore() for the exercise if you want.
Read up on std::istream::ignore()
cin.ignore() defaults to ignoring one character.
If you output your string each time, you'll see that in later cases the string is equal to "ey hi". The h is being dropped.
The value of the string held by cin drops its first character before being passed to getline.
Since you're using getline, you can simply remove the cin.ignore() from your loop and your program should work as intended.
However, you should also change your cin>>t; line. In this case, the ignore() is dropping the line return after the input value 2. A stringstream here allows for a getline(...) function, or alternatively you can use cin.ignore(str.max_size(), '\n');.
In the case of the stringstream, your code would become:
#include <sstream> // stringstream
#include <string> // std::string
#include <iostream> // cin
int main()
{
string str;
int t,length;
getline(cin, str);
std::stringstream stream;
stream << str;
if (!(stream >> t)) {
// Couldn't process to int
}
// cin>>t; // t is the number of test cases
// No longer need this line.
while(t--!=0)
{
// cin.ignore(); Drop this too
getline(cin,str);
length=str.size();
cout<<"length="<<length;
}
}
If you are not interested in whitespace,
then use getline(cin >> ws, str)
consider this code snippet
void make(int n)
{
std::string user_input;
std::istringstream iss(user_input);
char letter;
int index;
while(n>0)
{ cout<<n<<endl;
std::getline(std::cin, user_input);
while (iss >> letter >> index)
cout<<letter<<' '<<index;
n--;
}
}
int main()
{ int n;
cin>>n;
make(n);
return 0;
}
here loop is not running correctly
if i put n=5 then output is
5
//getline doesn't work
4
then getline works... why this
The reason why it's doing this, is because when you're calling getline(), it's taking what's in cin and putting it in the variable. However, when you initially called cin to take in the inital input, the newline character remained in the buffer after going into your make() function.
So when you enter the loop, the first getline() takes '\n' from cin, and the buffer was cleared. That's why it seems to "skip" the first iteration as it would seem.
So in order to get it to function correctly, you should clear your input buffer when you call your function using cin.ignore(), like so:
void make(int n)
{
cin.ignore(1000,'\n'); //ignores 1000 characters or until sees \n
std::string user_input;
std::istringstream iss(user_input);
char letter;
int index;
while(n>0)
{ cout<<n<<endl;
std::getline(std::cin, user_input);
while (iss >> letter >> index)
cout<<letter<<' '<<index;
n--;
}
}
int main()
{ int n;
cin>>n;
make(n);
return 0;
}
I haven't used c++ much recently, so at the moment, i'm not sure if there's a better way to handle this, but this should give you a good direction.