This question already has answers here:
Replace multiple spaces with one space in a string
(5 answers)
Closed 9 years ago.
I wrote a program which is supposed to remove excess spaces from a string. But it only shows characters before spaces. It finds a space and checks the character after that whether it is a space. Depending on excess spaces it shifts other characters over excess spaces. But output is very confusing.
input: "qwe(2 spaces)rt(one space)y"
output: "qwe(one space)rt(one space)y"
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
int main(){
string a;
cin >> a;
int len = a.length();
int new_len=len;
int z,s=0;
for(int i=0; i<new_len; i++){
if(a[i]==' '){
z=i+1;
s=0;
//Assigning the number of excess spaces to s.
while(a[z]==' '){
s++;
z++;
}
//doing the shifting here.
if(s>0){
for(int l=i+1; l<new_len-s; l++){
a[l]=a[s+l];
}
}
new_len-=s;
}
}
cout << a << endl;
cout << a.length();
system("pause");
return 0;
}
Most of your code is semi-pointless -- when you use the normal string extractor (stream >> string) it automatically skips across all consecutive leading white-space, and stops reading at the first whitespace character. As such, it's already doing almost everything the rest of your code is intended to accomplish. That leaves a much simpler approach to accomplishing the same task:
std::copy(std::istream_iterator<std::string>(std::cin),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(std::cout, " "));
This does have one problem: it'll leave one extra space at the end of the output. If you don't want that, you can use the infix_ostream_iterator I've posted previously. With that, you'd change the above to something like this:
std::copy(std::istream_iterator<std::string>(std::cin),
std::istream_iterator<std::string>(),
infix_ostream_iterator<std::string>(std::cout, " "));
If you're using C++11 doing this your way is overkill - you can just use a regex. Something like the following should do it (untested):
#include <regex>
#include <iostream>
#include <string>
using namespace::std;
int main(){
string a;
cin >> a;
regex r(" +");
a = regex_replace(a,r," ");
cout << a << endl;
cout << a.length();
system("pause");
return 0;
}
Your code is highly ineffective. Imagine a following string with 1,000,000 characters:
a a a a a a a...
Each time your algorithm encounters a second space, it goes through the whole string to shift it one char left. I would attempt another approach:
Create two iterators, like realPos and charPos. Set them to 0 at the beginning.
Create a variable, which stores a number of spaces encountered so far, like spacesSeen. Set it to 0.
Now, while realPos is lower than length of the whole string:
If string[realPos] != ' ' and charPos != realPos, make an assignment: string[charPos] = string[realPos]. Then increase both realPos and charPos by one. Set spacesSeen to 0.
If string[realPos] == ' ' and spacesSeen == 0, increase spacesSeen by one, copy characters and advance both iterators.
If string[realPos] == ' ' and spacesSeen > 0, then increase spacesSeen and then increase only realPos.
Now charPos marks the place where your final string ends, adjust strings size, such that it ends there.
In simpler words: copy the characters one by one and skip multiple spaces on the way.
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! :)
So I am still new to C++, and I'm trying to make a program that has the user input a string, and then my functions return the string in reverse case, all lower case, and then all uppercase. Instead I just keep receiving the first letter of the string back, always uppercase. Not sure what I am doing wrong. Any suggestions?
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
char answer[255] = "";
int max = strlen(answer);
void reverse() {
for (int i = 0; i < max; i++) {
if (islower(answer[i])) {
isupper(answer[i]);
}
else if (isupper(answer[i])) {
islower(answer[i]);
}
else if (isspace(answer[i])) {
isspace(answer[i]);
}
}
cout << answer[max];
}
void lower() {
for (int i = 0; i < max; i++) {
if (isupper(answer[i])) {
islower(answer[i]);
}
else {
answer[i] = answer[i];
}
}
cout << answer[max];
}
void upper() {
for (int i = 0; i < max; i++) {
if (islower(answer[i])) {
isupper(answer[i]);
}
else {
answer[i] = answer[i];
}
}
cout << answer[max];
}
int main() {
cout << "Please enter a word, or a series of words: " << endl;
cin >> answer[max];
reverse();
lower();
upper();
system("pause");
return 0;
}
islower(char) is just a built in function to check if the char is in lowercase or not. Same goes with isupper. It does not change the case of the character.
In order to convert to lowercase/uppercase, use tolower/toupper. This would return the character in the converted case. But, it is important that you need to assign the returned value to the character itself.
Refer to this answer for some more clarity related to islower, isupper, tolower and toupper.
And now coming to the point why it's printing just the 1st character: As #user4581301 has mentioned in his comment,
"cin >> answer[max]; will read exactly one character because answer[max] is exactly one character, the first character. In C++ you have to do things in order. For example, int max = strlen(answer); will provide an answer based on what is in that string at that time. Since the string was initialized one line earlier and contains an empty string, max will be 0."
Hence your cin should be cin >> answer. BUT, this will accept the 1st word of your sentence. In order to accept all the words including the spaces, use getline() instead. And for using this, answer should be declared as string answer instead of a char array.
This is how you accept a full sentence: getline(cin,answer);
And your variable max will give an error in a few compilers as being ambiguous. This is because of the using namespace std;. to avoid this, rename max to something else, like maxlen.
And finding the length of answer: It would be better if you call answer.length() after accepting the string from user rather than doing it globally.
Your working code should look something like this:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
string answer;
int maxlen;
void reverse() {
for (int i = 0; i < maxlen; i++) {
if (islower(answer[i])) {
answer[i] = toupper(answer[i]);
}
else if (isupper(answer[i])) {
answer[i] = tolower(answer[i]);
}
else if (isspace(answer[i])) {
answer[i]=' ';
}
}
cout << "Reversed string: " + answer << endl;
}
void lower() {
for (int i = 0; i < maxlen; i++) {
if (isupper(answer[i])) {
answer[i] = tolower(answer[i]);
}
else {
answer[i] = answer[i];
}
}
cout << "Lower case string: " + answer << endl;
}
void upper() {
for (int i = 0; i < maxlen; i++) {
if (islower(answer[i])) {
answer[i] = toupper(answer[i]);
}
else {
answer[i] = answer[i];
}
}
cout << "Upper case string: " + answer << endl;
}
int main() {
cout << "Please enter a word, or a series of words: " << endl;
getline(cin,answer);
cout << "Original string: " + answer << endl;
maxlen = answer.length();
reverse();
lower();
upper();
return 0;
}
With the output:
Please enter a word, or a series of words:
ReVeRsAl UPPER aNd lower
Original string: ReVeRsAl UPPER aNd lower
Reversed string: rEvErSaL upper AnD LOWER
Lower case string: reversal upper and lower
Upper case string: REVERSAL UPPER AND LOWER
cin >> answer[max];
will read exactly one character because answer[max] is exactly one character, the character in the array at position max.
max is 0 because you have to do things in order. For example,
int max = strlen(answer);
will provide the length of answer at that time this line is reached. Since the string was initialized one line earlier
char answer[255] = "";
and contains an empty string, max will be 0. This means answer[max] is answer[0] Nothing in the code ever changes max, so it will remain 0.
OK, say we change things a little and rather than reading into a single character, we read into answer as a string. You will need to
cin.getline(answer, sizeof(answer));
because
cin >> answer;
will read one whitespace-delimited token. One word. Your stated goal is to read more than one word. istream::getline will read everything it finds into the first parameter up to the end of the line or it finds the number of characters specified in the second parameter minus 1 (in order to reserve space for the string's null terminator). sizeof(answer) is literally the size of the answer array in bytes. We're operating in byte-sized characters so the count of characters and number of bytes are the same. Extra care must be taken if multibyte characters are being used.
This seems like a good place to recommend using std::string and std::getline instead. They make a large number of problems, such as the maximum number of characters that can be read, vanish for the vast majority of cases.
I'm not going to use them here, though because the assignment likely has a "No strings" policy.
So now that we have cin.getline(answer, sizeof(answer)); reading the user's input we can work on getting the size for max. We could strlen, but we could also use istream::gcount to get the number of characters read by getline.
main now looks something like
int main() {
cout << "Please enter a word, or a series of words: " << endl;
cin.getline(answer, sizeof(answer));
max = cin.gcount();
reverse();
lower();
upper();
system("pause");
return 0;
}
Whole bunch of stuff can go wrong at this point.
using namespace std; can wreak havoc on the max because of possible collisions with std::max. In general, avoid using namespace std; The few letters it saves you from typing often are recovered by the time wasted debugging the weird errors it can introduce.
isupper(answer[i]); doesn't do anything useful as others have noted in the comments. You want
answer[i] = toupper(static_cast<unsigned char>(answer[i]));
See Do I need to cast to unsigned char before calling toupper(), tolower(), et al.? for why that insane-and-pointless-looking cast may be necessary. Thank you HolyBlackCat for bringing that to my attention.
Self assignments like
answer[i] = answer[i];
are pointless for reasons that should be obvious once you stop and think about it.
Likewise
else if (isspace(answer[i])) {
isspace(answer[i]);
}
May not be particularly useful. If answer[i] is a space, set it to a space? It's already a space. What it would do is replace other forms of whitespace, tabs and carriage returns, with a space. Newline has already been picked off by getline. Also probably needs a cast similar to the one used in the toupper example above. I'm still reading up on that.
As hinted at above,
cout << answer[max];
is not effective. It prints out one character, and if max has been fixed, answer[max] will be the terminating null. Instead print out the whole array.
cout << answer;
General suggestions:
Don't write much code at a time. Write a few lines, a function at the most, before compiling and testing. If you had tested
int main() {
cout << "Please enter a word, or a series of words: " << endl;
cin >> answer[max];
cout << answer;
}
You would have immediately seen data was not being read correctly. and fixed it before proceeding. By allowing errors to build up, you make it harder to find any one bug. You may correctly fix a bug only to find the fix undone or concealed by another bug.
Avoid using global variables. Try to place variables in the smallest possible scope. In this case, move answer and max into main and pass them to the other functions as parameters. This makes it a lot easier to keep track of who set what variable and when. It also helps prevent accidental Variable Shadowing.
I want to take in a code, for example ABC and check whether the characters in the code appear in that exact order in a string, for example with the code ABC, and the string HAPPYBIRTHDAYCACEY, which meets the criteria. The string TRAGICBIRTHDAYCACEY with the code ABC however does not pass, because there's a "c" before the "b" after the "a". I want to use the find_first_of function to search through my string, but i want to check for any of the characters in "code", without knowing what characters are in "code" beforehand. Here is my program so far:
#include <iostream>
#include <string>
using namespace std;
int main() {
string code, str, temp;
int k = 0;
int pos = 0;
cin >> code >> str;
while (k < code.size()) {
pos = str.find_first_of(code,pos);
temp[k] = str[pos];
++k;
++pos;
}
cout << temp << endl; // debug. This is just outputs a newline when i
//run the program
if (temp == code) {
cout << "PASS" << endl;
}
else {
cout << "FAIL" << endl;
}
return 0;
}
I think your best bet is to find just the first character, once found, find the next in the remainder of the string, repeat until end of string or all characters found (and return false or true, respectively).
I don't think there's anything builtin for this. If the characters would need to appear directly after each other, you could use std::string::find() which searches for a substring, but that is not what you want.
I'm having trouble with this program. The program is supposed to tell the user the number of lines, words, characters, unique lines, and unique words there are in a given input. So far, words and characters are okay. However, if the user wants to input more than one line, how do I do that? The functions will only output the results of one line at a time, rather than adding the results of both lines together. Also, I can't get the Unique Lines and Unique Words to work properly. I just got into C++ so I don't really have much experience. Can someone please help me?
Problems:
Program reads one line at a time, so when the user inputs multiple times, the program produces the results separately rather than adding it together as one entity.
Unique Lines and Unique Words are not working. Any ideas how to implement it using the library used in the program.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <string>
using std::string;
#include <set>
using std::set;
// write this function to help you out with the computation.
unsigned long countLines()
{
return 1;
}
unsigned long countWords(const string& s)
{
int nw =1;
for (size_t i = 0; i < s.size(); i++)
{
if (s[i] == ' ') //everytime the function encounters a whitespace, count increases by 1)//
{
nw++;
}
}
return nw;
}
unsigned long countChars(const string& s)
{
int nc = 0;
for (size_t i = 0; i < s.size(); i++)
{
if ( s[i] != ' ') //everytime the function encounters a character other than a whitespace, count increases//
{
nc++;
}
}
return nc;
}
unsigned long countUnLines(const string& s, set<string>& wl)
{
wl.insert(s);
return wl.size();
}
unsigned long countUnWords(const string& s, set<string>& wl)
{
int m1 = 0;
int m2 = 0;
string substring;
for(m2 = 0; m2 <= s.size(); m2++){
if (m2 != ' ' )
substring = s.substr(m1,m2);
wl.insert(substring);
m1 = m2 + 2;}
}
return wl.size();
int unw = 0;
wl.insert(s);
unw++;
return unw;
}
int main()
{
//stores string
string s;
//stores stats
unsigned long Lines = 0;
unsigned long Words = 0;
unsigned long Chars = 0;
unsigned long ULines = 0;
unsigned long UWords = 0;
//delcare sets
set<string> wl;
while(getline(cin,s))
{
Lines += countLines();
Words += countWords(s);
Chars += countChars(s);
ULines += countUnLines(s,wl);
UWords += countUnWords(s);
cout << Lines << endl;
cout << Words<< endl;
cout << Chars << endl;
cout << ULines << endl;
cout << UWords << endl;
Words = 0;
Chars = 0;
ULines = 0;
UWords = 0;
}
return 0;
}
You are resetting your count variables to zero at the end of your getline while loop. This is why you are only getting results for one line. The user can input multiple lines in your program as it is right now you are just resetting the count.
I think you're headed in the right direction. In order to count unique lines and words you're gonna have to store every line and word in a data structure of some kind, I'd suggest an unordered_map. Each element in the map you'll have a counter for # of occurences of each line/word.
I don't want to give the answer away wholesale, but here are some ideas to get you started.
The function getline() can read in an entire line of input. Do this until there's no more input.
You can use a container like std::set (or better, std::unordered_set) to store the lines read in. Not the most efficient, but it keeps track of all your lines, and only stores the unique ones.
Each line can then be broken down into words. Consider using something like std::stringstream for this.
Store the words in a different std::unordered_set.
The number of unique lines (words) is simply the number of lines (words) stored in the containers. Use the .size() method to obtain this.
Doing the total number of lines, words, and characters can be computed as you read the data in, so I won't go into much detail there.
Each item is googleable, and you may choose to implement different parts differently (if you don't want to use a stringstream, you can always iterate over the line read, for example.) This should get you on the right track.
It's pretty easy to get fairly accurate counts, but can be surprisingly difficult to get correct counts for all of this.
The big problem is the character count. If you open the file (as you usually would) in text mode, the number of characters you count may not match what the OS thinks is there. For the obvious examples, under Windows a CR/LF pair will be translated to a single new-line character, so you'll typically count each line as one character shorter than it really is.
Technically, there's no way to deal with that entirely correctly either -- the translation from external to internal representation when a file is opened in text mode is theoretically arbitrary. At least in theory, opening in binary mode doesn't help a lot either; in binary mode, you can have an arbitrary number of NUL characters after the end of the data that was written to the file.
The latter, however, is pretty much theoretical these days (it was allowed primarily because of CP/M, which most people have long forgotten).
To read lines, but retain the line-end delimiters intact, you can use std::cin.get() instead of std::getline(), then read the delimiters separately from the line itself.
That gives us something like this:
#include <iostream>
#include <set>
#include <string>
#include <iterator>
#include <sstream>
#include <fstream>
int main(int argc, char **argv) {
static char line[4096];
unsigned long chars = 0;
unsigned long words = 0;
unsigned long lines = 0;
std::set<std::string> unique_words;
std::ifstream in(argv[1], std::ios::binary);
while (in.get(line, sizeof(line), '\n')) {
++lines;
chars += strlen(line);
std::istringstream buffer(line);
std::string word;
while (buffer >> word) {
++words;
unique_words.insert(word);
}
while (in.peek() == '\n' || in.peek() == '\r') {
++chars;
in.ignore(1);
}
}
std::cout << "words: " << words << "\n"
<< "lines: " << lines << "\n"
<< "chars: " << chars << "\n"
<< "unique words: " << unique_words.size() << "\n";
}
Note that although this does answer that the OP actually asked at least for most typical OSes (Linux, *BSD, MacOS, Windows), it's probably not what he really wants. My guess is that his teacher isn't really asking for this level of care to try to get an accurate character count.
Also note that if you should encounter a line longer than the buffer, this can still give an inaccurate count of lines -- it'll count each buffer-full of data as a separate line, even if it didn't find a line-delimiter. That can be fixed as well, but it adds still more complexity to a program that's almost certainly already more complex than intended.
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);