This is my code here i am trying to find the biggest length of same length characters at a time like "a a a bb bb bc sa sa a a" so answer is 5 for two characters at a time for 5 times adjacently .
this is my code , my question is that when i am trying to take the input , for my first input it is not going to getline but printf in last lines and then it takes a line and prints output
like if i give
5 it writes 1 then it takes getline , but i want it to take getline first rather than printf, in this way for my 5 input it prints 1 and 4 desired outputs .i want 5 desired can you tell me why..
#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
int main()
{
int a,j;
scanf("%d",&a);
for(j=0;j<a;j++)
{
vector<int> v;
string s;
getline(cin,s);
int i,cnt =0;
for(i=0;i<s.length();i++)
{
if(s[i] != ' ')
{
cnt++;
}
else
{
v.push_back(cnt);
cnt =0;
}
}
v.push_back(cnt);
int k=0;
int ps =0;
int sp=0;
while(k<v.size()-1)
{
if (v[k+1] - v[k] == 0)
{
sp++;
k++;
}
else
if (sp >= ps)
{
ps = sp;
k++;
sp=0;
}
else
{
k++;
sp=0;
}
}
if (sp<ps)
printf("%d",ps+1);
else
printf("%d",sp+1);
}
return 0;
}
You shouldn't be mixing scanf with getline, try to only use one or the other (and getline is a better option).
What is happening is that scanf stops parsing once it has finished reading an int. It does not consume the end of line character you type, or anything else you could have entered after that number. So getline picks up whatever was left on that first line (possibly just the newline char).
A "quick" but dirty fix would be to change your scanf call so that it swallows the whitespace after the int:
scanf("%d ",&a);
// ^ notice the space there
But that's not a real fix. Use getline and a string stream (in <sstream>) to get the first number, and your code will work as you intend it to. You'll find examples of using the istringstream to extract a number in this FAQ: How to convert a number to string and vice versa in C++
You might also be interested in this other question:
Split a string in C++?, the answers demonstrate ways to split a string that are less error-prone than what you're doing here.
How are you entering everything exactly? I think the problem may be that your getline() is reading your last [enter] off of the stream, thus automatically putting an empty string into s. That would result in the 1 you're getting. Try this for your scanf:
scanf("%d\n",&a)
That should absorb the [enter].
Related
I am trying to skip the spaces in my code using getline();
I think I solved the spacing problem, but I'm trying to make the code check from the beginning of the word and the end of the word at the same time, so that when I type sentences like "ufo tofu" it will come back as a palindrome.
I've tried removing the spaces, but it only causes the system to return me an error.
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string userInput;
int startInput;
int endInput;
bool isPalindrome = true;
startInput = userInput.length();
getline (cin, userInput);
cin.ignore();
for (int i = 0; i<(startInput/2); i++){
if (userInput[i] != userInput[(startInput -1) -i])
isPalindrome = false;
}
if (isPalindrome){
cout << userInput << " is a palindrome" << endl;
}
else {
cout << userInput << " is not a palindrome" << endl;
}
return 0;
}
I am trying to make the output come back as "is not a palindrome" when I submit my code to be graded.
These are the two errors that are coming back;
4: Compare output
0 / 2
Output differs. See highlights below.
Special character legend
Input
statistics
Your output
statistics is a palindrome
Expected output
statistics is not a palindrome
6: Compare output
0 / 2
Output differs. See highlights below.
Special character legend
Input
evil is alive
Your output
evil is alive is a palindrome
Expected output
evil is alive is not a palindrome
string s;
do {
getline(cin, s);
}while(s.empty());
s.erase((remove(s.begin(),s.end(),' ')),s.end());
cout<<s<<endl;
Let's say your string s is ufo tofu. It will after erasing all spaces become ufotofu. That way you can easily check if it's palindrome or not.
How does this thing work ?
Well we declare a string called s. In that string, we will store our ufo tofu input.
We use do-while loop to input our "sentence" into a string. We could use just getline(cin, s);, but if you pressed enter-key once, it would stop your program.
Next thing, we use function combination of functions remove and erase: As the beginning parameter we use function remove, which finds all the spaces in the string, pushes them to the end of the container (in our case string s), and returns beginning iterator of that "pushing", and the second parameter tells us to remove every single element of container from that beginning iterator to the end.
We just print out the string, but now without spaces!
I think this is really simple way to do it, but if it can't be useful to you, I am sorry for wasting your time reading all of this! :)
I am a complete beginner so the code may seem to be easy, but I cannot find a solution why it returns such values as:
input: kkkk
output:
14
kkkkřřřř╩┬ëŢ
Suprisingly the code works fine with online compilators, but not with the Visual Studio.
#include<iostream>
#include<string.h>
int main()
{
char word[20];
std::cin >> word;
int length = strlen(word);
int p = length - 1, i = 0;
char *var=new char [length];
while (i < length&&p>=0)
{
var[i]= word[p];
p--;
i++;
}
std::cout <<strlen(var)<<endl<< var;
if (!strcmp(var, word)) std::cout << "\nThe word is a palindrome";
return 0;
}
I can not use strings because my University doesn't allow to do so. I also know there are many different ways to attend to this problem but I just really want know what I have done wrong in this one :/
Your "copy routine" copies each character, but it does not copy the string termination character. Note that C-style strings as used in functions like strlen or strcmp need to be 0-terminated, and even cout <<, when getting a parameter of type char*, treats this as a C-style string: It will read until finding the terminating '\0', and if you do not write one, it will read beyond the boundaries you think it should do.
If your write
...
}
var[length] = '\0';
std::cout <<strlen(var)<<endl;
...
it should work.
I would like to make a space/return check for a string array. And a bit more I guess...
The user enters two lines, both being strings. To accommodate for these two lines, rather than making two separate string variables, I made a string array called string x[2]. Then the input gets combined into one variable called string combined and then outputs everything on one line.
Anyways, I would like the program to allow each line to have multiple strings, i.e. line one is I like tuna and line two is blah blah. I tried to make this a multidimensional array like x[2][3] but then if they enter only one word in a line then this forces them to enter in more lines until the array is completely filled up.
I want the user to enter up to 3 words in each line and a maximum of two lines. So doesn't that mean I have to check for spaces and returns? If so, how?
I don't want to make this post codeless, so for some point of reference, here is my original code which only lets them enter one word per line and two lines:
int main()
{
string x[2], combined;
for (int i = 0; i < 2; ++i)
{
cin >> x[i];
if (i == 0) combined = x[0];
else
combined += " " + x[i];
}
cout << combined << endl;
}
/*
Program:
Hello
World
Hello World
Press any key to continue...
I apologize if this post/question is very ambiguous and seems like I haven't put much thought in, but I'm a beginner and haven't been able to figure this one out. Thanks for your time!
Use getline
for (int i = 0; i < 2; ++i)
{
getline(cin, x[i]);
}
Use getline to read entire line of input
string x[2];
cout<<"input first string"<<endl;
getline(cin, x[0]);
cout<<"input second string"<<endl;
getline(cin, x[1]);
cout<<"Printing first string "<<x[0]<<endl;
cout<<"Printing second string "<<x[1]<<endl;
there is one similar problem in C. there you can't use scanf() if user inputs the string with spaces (cause there will be an error), you have to use gets(), which is unsafe.
I am trying to write a console program, which gets a number from the input and puts it into an array. The read in lasts as long as the user does not hit the "space" button. I have tried several things, but my program won't compare the input with the ASCII code of "space". Thanks in advance!
#include <iostream>
using namespace std;
int main()
{
int fabcd[25],number_of_items = 0;
cout << "The read in loop lasts while you don't hit space:\n";
while((char)cin.get() != 32)
{
cin >> fabcd[number_of_items];
number_of_items++;
}
return 0;
}
There are several problems with your code. The most fundamental
is that you do two inputs each time through the loop, the first
in the while, and the second using >> in the loop. Note too
that the second will skip any spaces, then convert the input to
an integer. If the input cannot be legally converted to an
integer (e.g. the next character is an 'a'), the input goes
into an error state, and cin.get() will always return EOF.
And of course, if you are entering numbers, you can easily
enter more than 25, and overrun the buffer.
If you just want to enter a sequence of numbers, then:
std::vector<int> fabcd;
int tmp;
while ( std::cin >> tmp ) {
fabcd.push_back( tmp );
}
is all you need. (The numbers must be separated by white
space.) If you want to enter the digits, up until you
encounter a white space, something like the following should
work:
std::vector<int> digits;
int tmp = std::cin.get();
while ( tmp != EOF && ! std::isspace( tmp ) ) {
digits.push_back( tmp /* or tmp - '0' */ );
tmp = std::cin.get();
}
Notice that the results of std::cin.get() are assigned to an
int, not a char. This function returns an int
intentionally, because it must be able to return the out of band
value EOF. There are a couple of variants on this: if you use
std::cin::peek(), instead of std::cin::get(), you'll not
actually extract the character (which you'll have to do in the
loop); and there is also std::get( char& ), which extract the
character into the given char, provided it isn't at EOF.
Using this function, the loop would be:
std::vector<int> digits;
char tmp;
while ( std::get( tmp ) && ! std::isspace( tmp ) ) {
digits.push_back( tmp );
}
(You might also want to use std::isdigit, instead of !
std::ispace to control the loop.)
EDIT:
One last point: the actual numeric code for a space or whatever
depends on the implementation, and is not necessarily 32.
Also, you'll want to handle tabs and newlines similarly. You
should always use the isspace, etc. functions. Or if you
really do want to check for a space, and only a space, compare
with ' ', and not 32.
(char)13 ist the carriage return not the space.
isn't the point that you would do:
((char)cin.Get()) !=' '
The acii code for space is 32. So you should substitute 64 or 13, which is carraiage return to 32:
while((char)cin.get() != 32)
However the problem might be that cin may stop on some characters for example whitespace: You can disable this behaviour by setting: cin.unsetf(ios::skipws);
according to C++, user input check for '\0' stops at spaces?
try this :
#include <iostream>
#include <conio.h >
using namespace std;
int main()
{
int fabcd[25],number_of_items = 0;
cout << "The read in loop lasts while you don't hit space:\n";
while( _kbhit() != 32 )
{
char ch =getche();
if (ch != 32 )
{
cin >> fabcd[number_of_items];
number_of_items++;
}
else
break;
}
cout << "\nnumber of items:"<<number_of_items;
cin.get();
cin.get();
return 0;
}
Here is the answer:
int fabcd[25],number_of_items = 0;
cout << "The read in loop lasts while you don't hit space:\n";
char a;
while((a=cin.get()) != ' ')
{
fabcd[number_of_items]=a;
number_of_items++;
}
return 0;
This may be a total beginner's question, but I have yet to find an answer that works for me.
Currently, I'm writing a program for a class that takes in a user's input (which can be one or more numbers separated by spaces), then determines whether the number is prime, perfect, or neither. If the number is perfect, then it will display the divisors.
Thus far, I've already written the code for the prime, perfect, and listing the divisors. I'm stuck on the input portion of my program. I don't know how to get the input that's separated by spaces to go through my loops one at a time.
This is my current program:
cout<<"Enter a number, or numbers separated by a space, between 1 and 1000."<<endl;
cin>>num;
while (divisor<=num)
if(num%divisor==0)
{
cout<<divisor<<endl;
total=total+divisor;
divisor++;
}
else divisor++;
if(total==num*2)
cout<<"The number you entered is perfect!"<<endl;
else cout<<"The number you entered is not perfect!"<<endl;
if(num==2||num==3||num==5||num==7)
cout<<"The number you entered is prime!"<<endl;
else if(num%2==0||num%3==0||num%5==0||num%7==0)
cout<<"The number you entered is not prime!"<<endl;
else cout<<"The number you entered is prime!"<<endl;
return 0;
It works, but only for a single number. If anyone could help me to get it to be able to read multiple inputs separated by spaces, it'd be greatly appreciated. Also, just a side note, I do not know how many numbers will be entered, so I can't just make a variable for each one. It will be a random amount of numbers.
Thanks!
By default, cin reads from the input discarding any spaces. So, all you have to do is to use a do while loop to read the input more than one time:
do {
cout<<"Enter a number, or numbers separated by a space, between 1 and 1000."<<endl;
cin >> num;
// reset your variables
// your function stuff (calculations)
}
while (true); // or some condition
I would recommend reading in the line into a string, then splitting it based on the spaces. For this, you can use the getline(...) function. The trick is having a dynamic sized data structure to hold the strings once it's split. Probably the easiest to use would be a vector.
#include <string>
#include <vector>
...
string rawInput;
vector<String> numbers;
while( getline( cin, rawInput, ' ' ) )
{
numbers.push_back(rawInput);
}
So say the input looks like this:
Enter a number, or numbers separated by a space, between 1 and 1000.
10 5 20 1 200 7
You will now have a vector, numbers, that contains the elements: {"10","5","20","1","200","7"}.
Note that these are still strings, so not useful in arithmetic. To convert them to integers, we use a combination of the STL function, atoi(...), and because atoi requires a c-string instead of a c++ style string, we use the string class' c_str() member function.
while(!numbers.empty())
{
string temp = numbers.pop_back();//removes the last element from the string
num = atoi( temp.c_str() ); //re-used your 'num' variable from your code
...//do stuff
}
Now there's some problems with this code. Yes, it runs, but it is kind of clunky, and it puts the numbers out in reverse order. Lets re-write it so that it is a little more compact:
#include <string>
...
string rawInput;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while( getline( cin, rawInput, ' ') )
{
num = atoi( rawInput.c_str() );
...//do your stuff
}
There's still lots of room for improvement with error handling (right now if you enter a non-number the program will crash), and there's infinitely more ways to actually handle the input to get it in a usable number form (the joys of programming!), but that should give you a comprehensive start. :)
Note: I had the reference pages as links, but I cannot post more than two since I have less than 15 posts :/
Edit:
I was a little bit wrong about the atoi behavior; I confused it with Java's string->Integer conversions which throw a Not-A-Number exception when given a string that isn't a number, and then crashes the program if the exception isn't handled. atoi(), on the other hand, returns 0, which is not as helpful because what if 0 is the number they entered? Let's make use of the isdigit(...) function. An important thing to note here is that c++ style strings can be accessed like an array, meaning rawInput[0] is the first character in the string all the way up to rawInput[length - 1].
#include <string>
#include <ctype.h>
...
string rawInput;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while( getline( cin, rawInput, ' ') )
{
bool isNum = true;
for(int i = 0; i < rawInput.length() && isNum; ++i)
{
isNum = isdigit( rawInput[i]);
}
if(isNum)
{
num = atoi( rawInput.c_str() );
...//do your stuff
}
else
cout << rawInput << " is not a number!" << endl;
}
The boolean (true/false or 1/0 respectively) is used as a flag for the for-loop, which steps through each character in the string and checks to see if it is a 0-9 digit. If any character in the string is not a digit, the loop will break during it's next execution when it gets to the condition "&& isNum" (assuming you've covered loops already). Then after the loop, isNum is used to determine whether to do your stuff, or to print the error message.
You'll want to:
Read in an entire line from the console
Tokenize the line, splitting along spaces.
Place those split pieces into an array or list
Step through that array/list, performing your prime/perfect/etc tests.
What has your class covered along these lines so far?
int main() {
int sum = 0;
cout << "enter number" << endl;
int i = 0;
while (true) {
cin >> i;
sum += i;
//cout << i << endl;
if (cin.peek() == '\n') {
break;
}
}
cout << "result: " << sum << endl;
return 0;
}
I think this code works, you may enter any int numbers and spaces, it will calculate the sum of input ints
std::vector<int> num{};
int buf;
do{
std::cin >> buf;
num.push_back(buf);
}while(std::cin.peek() == ' ');
In C language you can to it using scanf like this:
scanf('%d %d',&a,&b);