#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
int T;
char J[100], S[100];
int count=0;
cin >> T;
while(T--)
{
cin.getline(J,100);
cin.getline(S,100);
puts(J);
puts(S);
for(int i=0; J[i]!='\0'; i++)
{
for(int j=0; S[j]!='\0'; j++)
{
count++;
for(int k=j; S[k]!='\0'; k++)
S[k]=S[k+1];
break;
}
}
cout << count;
}
return 0;
}
I am taking input string in J,S but during execution of program it skips the second input from the console cin.getline
I takes the test cases then takes the Strings J and S
it takes J successfully but fails to get S string ?
you need to be using a string , std::string, and calling getline as in
std::string s,j;
std::getline(std::cin,j);
std::getline(std::cin,s);
and then if you want to iterate over the contents of the strings by individual characters
for(auto i = std::begin(s); i != std::end(s); ++i)
{
std::cout << *i << std::endl;
}
use the iterators, and deference them to get the actual character values. Stay way from c strings as much as possible.
This code:
int T;
// ...
cin>>T;
...reads an int from standard input. To get it to read that int, you need to press the enter key, but this code does not remove that enter from the input buffer. Then...
cin.getline(J,100);
This tries to read a string from the input buffer, up to the first new-line character. It removes that new-line from the input buffer, but does not include it as part of the string. As such, if you don't look really closely, it appears to do essentially nothing -- i.e., you end up with an empty string.
You generally want to stick to either field-oriented input (like your cin >> T; or else line-oriented input (getline). Mixing the two, however, can be a bit tricky, especially if the getline comes after the field-oriented input. Don't get me wrong: it can work -- and work perfectly well at that, but you need to know what you're doing, and even then it can still surprise you now and again.
As noted in my comment (and #johnathon's answer) you also generally want to use std::getline to read an std::string, instead of std::cin.getline with an array of char. The latter is clumsy to deal with, even at best.
My own preference is (as a rule) to use line-oriented input throughout if you're going to use it anywhere.
std::string temp;
std::getline(std::cin, temp);
int T = lexical_cast<int>(temp);
while (T--) {
std::string j;
std::getline(std::cin, j);
// ...
As an aside, I'd also avoid using T as a name of an ordinary variable in C++. It's quite commonly used as the name of a template parameter; using it for "normal" variables is more likely to lead to confusion, especially for more advanced programmers who use templates more often.
(1)Use getchar() between cin>>T and while (T--)
as
int T;
char J[100] , S[100];
int count=0;
cin>>T;
getchar();
while(T--){
cin.getline(J,100);
cin.getline(S,100);
(2).
You can also resolve your problem in following way::
char T[10];
char J[100] , S[100];
int count=0;
getline(T,10);
while((atoi(T))--){
cin.getline(J,100);
cin.getline(S,100);
use Any 1 of them ,it will fix your problem.
Related
I am a beginner in c++ and I want to enter a string as character by character into an array , so that I can implement a reverse function .. However unlike C when the enter is hit a '\n' is not insterted in the stream.. how can I stop data from being entered ?
my code is :
#include<iostream>
#include<array>
#define SIZE 100
using namespace std;
char *reverse(char *s)
{
array<char, SIZE>b;
int c=0;
for(int i =(SIZE-1);i>=0;i--){
b[i] = s[c];
c++;
}
return s;
}
int main()
{
cout<<"Please insert a string"<<endl;
char a[SIZE];
int i=0;
do{
cin>>a[i];
i++;
}while(a[i-1]!= '\0');
reverse(a);
return 0;
}
When you read character by character, it really reads characters, and newline is considered a white-space character.
Also the array will never be terminated as a C-style string, that's not how reading characters work. That means your loop condition is wrong.
To begin with I suggest you start using std::string for your strings. You can still read character by character. To continue you need to actually check what characters you read, and end reading once you read a newline.
Lastly, your reverse function does not work. First of all the loop itself is wrong, secondly you return the pointer to the original string, not the "reversed" array.
To help you with the reading it could be done something like
std::string str;
while (true)
{
char ch;
std::cin >> ch;
if (ch == '\n')
{
break; // End loop
}
str += ch; // Append character to string
}
Do note that not much of this is really needed as shown in the answer by Stack Danny. Even my code above could be simplified while still reading one character at a time.
Since you tagged your question as C++ (and not C) why not actually solve it with the modern C++ headers (that do exactly what you want, are tested, save and work really fast (rather than own functions))?
#include <string>
#include <algorithm>
#include <iostream>
int main(){
std::string str;
std::cout << "Enter a string: ";
std::getline(std::cin, str);
std::reverse(str.begin(), str.end());
std::cout << str << std::endl;
return 0;
}
output:
Enter a string: Hello Test 4321
1234 tseT olleH
I need to make a program that reads n numbers in a row. For example, the user first puts in a list of 2 numbers like this:
P n
I managed to read those with scanf but now I need to read the n following numbers, these numbers are given in a row as follows.
1 6 3 99 ... n times
These numbers must be read all at once (or give the impression of).
I already tried using
while(getline(cin,str)){
// do something with str
}
As explained in this thread but I need the actions inside the while loop to stop when I hit the intro key. With my current implementation they don't stop, it just keeps waiting for more lines to read.
In summary:
First, user must be able to input two numbers (P and n)(done!) then hit enter and start typing a list of n numbers (not done!).
Here is my code.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(void){
int P,n;
scanf("%d %d",&P,&n);
string val;
int score[P];
int i;
for(i=0;i<P;i++){
score[i]=0;
}
while(getline(cin,val)){
printf("Val=%s\n",val.c_str());
stringstream stream(val);
int local;
while(stream >> local){
score[local]=score[local]+1;
printf("%d-%d\n",local,score[local]);
}
}
for(i=0;i<P;i++){
printf("%d-%d\n",i,score[i]);
}
return 0;
}
Use scanf() inside the n times loop instead of getline().
for(int i = 0; i < n; i ++){
scanf("%d",&variable);
}
Not sure I understood your question, but this code will read 2 numbers, then a line and then finish.
using namespace std;
int main(){
int P,n;
cin >> P;
cin >> n;
int *score = new int[P];
for(int i=0;i<P;i++){
score[i]=0;
}
int num;
string val;
cin.ignore();
getline(cin, val);
istringstream stream(val);
while (stream >> num) {
printf("Val = %d\n", num);
score[num]=score[num]+1; // potential segmentation fault here in your code
printf("%d-%d\n",num,score[num]);
}
delete [] score;
return 0;
}
The fault would occur because you are assuming that the number on the line is smaller than P, which is the size of the array. However, the following input would cause error:
1 2
5
This question is almost a classic. The classic question has this code:
cin >> n;
getline(cin, s);
and then the author is puzzled why s is empty. Your variation does the same, although it also uses C stdio function to make matters more confusing. The problem is that the first call is a field-based input, which will read a single value n and leave any other input in the buffer! If the user entered 42 and hit enter, the remaining input is the newline. The second getline() call then reads an empty string and discards the newline.
For interaction with the user, only use getline() and then try to parse each line. Using stringstreams or sscanf(), since you seem familiar with it, are both valid options. However, if you only want to read the input an not really interact, David Weston's suggestion is also a good one and probably the easiest one, too. However, since you're using C++, I'd suggest using cin >> variable instead.
As I declared a structure array: struct name data[5];
When I try to take input using cin.getline(data[i].full_name,75) (which I need) then after first time it skips the char input. I searched on this site and used fgets but was of no use.
The code is :
#include<iostream>
using namespace std;
struct name
{
char full_name[75];
int number;
};
void input(struct name data[])
{
int i=0;
while(i<5)
{
cout<<"Enter the name: ";
fgets(data[i].full_name,75,stdin);
OR
cin.getline(data[i].full_name,75)
cout<<"Enter the number: ";
cin>>data[i].number;
i++;
}
}
int main()
{
int times=0;
struct name data[5];
input(data);
}
here is my suggestion hope it helps:
void input(struct name data[])
{
int i=0;
int number;
char asciNumber[75];
while(i<5)
{
cout<<"Enter the name: ";
cin.getline(data[i].full_name,75);
cout<<"Enter the number: ";
cin.getline(asciNumber,75);
try
{
number = atoi(asciNumber);
data[i].number = number;
}
catch (...)
{
//cout << "error in number parsing" << endl;
// i think its important to check validity of std input\
}
i++;
}
}
Well, for starters, you can't use fgets() here, at all. The results of mixing the C library's stdin-based functions, and C++ library's std::cin are undefined.
But your real problem is this:
cin>>data[i].number;
Your intent here is to read a line of text containing a number.
As you know, each line of text is terminated by a newline.
The >> operator will read the entered number, but it will not actually read the newline character that follows it.
As a result of that, on the next iteration of the loop:
cin.getline(data[i].full_name,75)
All this will do, then, is immediately read the newline character after the entered number, instead of the next line of text.
You will need to replace your usage of the >> operator with another getline() that reads the next line of text into a std::string, and then use std::istringstream to convert it to a number.
That's the cleanest implementation. There are a couple of other possibilities, such as manually reading past the newline character after the number, or another, throw-away call to std::getline().
When I load less than 5 chars, it is ok. But if i load more than five chars my program crash.
How can i protect before that?
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
char tab[5];
int tab2[5];
char *wsk = tab;
int i = 0;
cin >> tab;
while (true) {
cin >> tab2[i];
if (tab2[i] == 0) break;
i++;
}
i = 0;
while (true) {
if (tab2[i] ==0) break;
wsk += tab2[i];
cout << *wsk;
i++;
}
return 0;
}
You don;t want to limit it to 5.
What you really want is to make sure the read works and never crashes.
The reason you don't want to stop reading at 5 characters is that if the user enters more than 5 characters you have stopped reading in the middle of their input and you now have to write code to find the end of this input and then continue. Writting code to fix the input stream is hard. Rather take input validate (the user may have typed crap and you can generate an error message) but you will be in the correct place to continue reading for the next input operation.
char tab[5];
cin >> tab; // Fails if you read more than 4 input characters
// (because it will add '\0' on the end)
Why not use a self expanding destination structure.
std::string tab;
std::cin >> tab; // Read one word whatever the size.
But what about the array.
No more difficult. Here you want an array that re-sizes. Guess what we have std::vector
int tab2[5];
while (true) {
cin >> tab2[i]; // Fails on the 6 number you input.
// STUFF
}
The loop can be written like this:
std::vector<int> tab2;
while (true) {
int val;
cin >> val;
tab2.push_back(val);
// STUFF
}
Instead of:
while (true)
put:
while (i < 5)
For C-style arrays, you have to set the width of the input stream to the number of characters allotted to the buffer, otherwise it will be possibly for you to write past the end of the array and get a buffer overflow. This is typically done using ios_base::width:
std::cin.width(5);
std::cin >> buffer;
You can also use the manipulator std::setw:
std::cin >> std::setw(5) >> buffer;
These will both set the maximum width of the stream to 5 characters. The width will be reset to its default after the first input operation.
Your loop condition should be
while(i < 5)
Also a for loop would fit perfectly
for(int i = 0; i < 5; i++) {
// body
}
You can use the algorithms part of the STL to bound your reads.
for example :
int main(){
char c[5];
auto newEnd = std::copy_n(std::istream_iterator<char>(std::cin), 5, std::begin(c));
// if newEnd != c + 5 then it failed to read 5 characters
}
The standard input is a stream. You don't get to decide what's in it. All you can do is read from it and see what you get -- either you get some data, or you learn that the stream has ended.
If you really only want to read five bytes, you can use std::cin.read(tab, 5); you must then call std::cin.gcount() to see how many bytes have actually been read and only consume as many bytes.
Alternatively, you can use C++'s dynamic containers and use std::getline(std::cin, line) to read into an std::string line as much data as is available up to a newline.
In either event, you first do the reading, then check whether and how much you actually read, and then check if what you read is of the form you expected (e.g. alphanumeric).
Say we have a code:
int main()
{
char a[10];
for(int i = 0; i < 10; i++)
{
cin>>a[i];
if(a[i] == ' ')
cout<<"It is a space!!!"<<endl;
}
return 0;
}
How to cin a Space symbol from standard input? If you write space, program ignores! :(
Is there any combination of symbols (e.g. '\s' or something like this) that means "Space" that I can use from standard input for my code?
It skips all whitespace (spaces, tabs, new lines, etc.) by default. You can either change its behavior, or use a slightly different mechanism. To change its behavior, use the manipulator noskipws, as follows:
cin >> noskipws >> a[i];
But, since you seem like you want to look at the individual characters, I'd suggest using get, like this prior to your loop
cin.get( a, n );
Note: get will stop retrieving chars from the stream if it either finds a newline char (\n) or after n-1 chars. It stops early so that it can append the null character (\0) to the array. You can read more about the istream interface here.
#include <iostream>
#include <string>
int main()
{
std::string a;
std::getline(std::cin,a);
for(std::string::size_type i = 0; i < a.size(); ++i)
{
if(a[i] == ' ')
std::cout<<"It is a space!!!"<<std::endl;
}
return 0;
}
To input AN ENTIRE LINE containing lot of spaces you can use getline(cin,string_variable);
eg:
string input;
getline(cin, input);
This format captures all the spaces in the sentence untill return is pressed
Use cin.get() to read the next character.
However, for this problem, it is very inefficient to read a character at a time. Use the istream::read() instead.
int main()
{
char a[10];
cin.read(a, sizeof(a));
for(int i = 0; i < 10; i++)
{
if(a[i] == ' ')
cout<<"It is a space!!!"<<<endl;
}
return 0;
}
And use == to check equality, not =.
Using cin's >> operator will drop leading whitespace and stop input at the first trailing whitespace. To grab an entire line of input, including spaces, try cin.getline(). To grab one character at a time, you can use cin.get().
I thought I'd share the answer that worked for me. The previous line ended in a newline, so most of these answers by themselves didn't work. This did:
string title;
do {
getline(cin, title);
} while (title.length() < 2);
That was assuming the input is always at least 2 characters long, which worked for my situation. You could also try simply comparing it to the string "\n".
Try this all four way to take input with space :)
#include<iostream>
#include<stdio.h>
using namespace std;
void dinput(char *a)
{
for(int i=0;; i++)
{
cin >> noskipws >> a[i];
if(a[i]=='\n')
{
a[i]='\0';
break;
}
}
}
void input(char *a)
{
//cout<<"\nInput string: ";
for(int i=0;; i++)
{
*(a+i*sizeof(char))=getchar();
if(*(a+i*sizeof(char))=='\n')
{
*(a+i*sizeof(char))='\0';
break;
}
}
}
int main()
{
char a[20];
cout<<"\n1st method\n";
input(a);
cout<<a;
cout<<"\n2nd method\n";
cin.get(a,10);
cout<<a;
cout<<"\n3rd method\n";
cin.sync();
cin.getline(a,sizeof(a));
cout<<a;
cout<<"\n4th method\n";
dinput(a);
cout<<a;
return 0;
}
I have the same problem and I just used cin.getline(input,300);.
noskipws and cin.get() sometimes are not easy to use. Since you have the right size of your array try using cin.getline() which does not care about any character and read the whole line in specified character count.