Trying to take an input string and remove the spaces from it. Except when it reaches a white space it deletes everything after that as well.
Here's my code (got it off a similar topic on stackoverflow):
string removeSpaces(string s){
s.erase(remove(s.begin(),s.end(), ' '),s.end());
return s;
}
For instance, if I input "1 +1", it returns "1". How could I fix this?
Here's a full example of what I tried:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string input;
string removeSpaces(string s){
s.erase(remove(s.begin(),s.end(), ' '),s.end());
return s;
}
int main(){
getline(cin, input);
removeSpaces(input);
cout << input;
}
That returns a string identical to the input with no spaces removed.
The function removeSpaces takes the input by value (it creates a copy) so it doesn't change the input string. The string with spaces removed is returned from the function so you need to use that instead. Try:
string output = removeSpaces(input);
cout << output;
Related
I am creating a function that splits a sentence into words, and believe the way to do this is to use str.substr, starting at str[0] and then using str.find to find the index of the first " " character. Then update the starting position parameter of str.find to start at the index of that " " character, until the end of str.length().
I am using two variables to mark the beginning position and end position of the word, and update the beginning position variable with the ending position of the last. But it is not updating as desired in the loop as I currently have it, and cannot figure out why.
#include <iostream>
#include <string>
using namespace std;
void splitInWords(string str);
int main() {
string testString("This is a test string");
splitInWords(testString);
return 0;
}
void splitInWords(string str) {
int i;
int beginWord, endWord, tempWord;
string wordDelim = " ";
string testWord;
beginWord = 0;
for (i = 0; i < str.length(); i += 1) {
endWord = str.find(wordDelim, beginWord);
testWord = str.substr(beginWord, endWord);
beginWord = endWord;
cout << testWord << " ";
}
}
It is easier to use a string stream.
#include <vector>
#include <string>
#include <sstream>
using namespace std;
vector<string> split(const string& s, char delimiter)
{
vector<string> tokens;
string token;
istringstream tokenStream(s);
while (getline(tokenStream, token, delimiter))
{
tokens.push_back(token);
}
return tokens;
}
int main() {
string testString("This is a test string");
vector<string> result=split(testString,' ');
return 0;
}
You can write it using the existing C++ libraries:
#include <string>
#include <vector>
#include <iterator>
#include <sstream>
int main()
{
std::string testString("This is a test string");
std::istringstream wordStream(testString);
std::vector<std::string> result(std::istream_iterator<std::string>{wordStream},
std::istream_iterator<std::string>{});
}
Couple of issues:
The substr() method second parameter is a length (not a position).
// Here you are using `endWord` which is a poisition in the string.
// This only works when beginWord is 0
// for all other values you are providing an incorrect len.
testWord = str.substr(beginWord, endWord);
The find() method searches from the second paramer.
// If str[beginWord] contains one of the delimiter characters
// Then it will return beginWord
// i.e. you are not moving forward.
endWord = str.find(wordDelim, beginWord);
// So you end up stuck on the first space.
Assuming you got the above fixed. You would be adding space at the front of each word.
// You need to actively search and remove the spaces
// before reading the words.
nice things you could do:
Here:
void splitInWords(string str) {
You are passing the parameter by value. This means you are making a copy. A better technique would be to pass by const reference (you are not modifying the original or the copy).
void splitInWords(string const& str) {
An Alternative
You can use the stream functionality.
void split(std::istream& stream)
{
std::string word;
stream >> word; // This drops leading space.
// Then reads characters into `word`
// until a "white space" character is
// found.
// Note: it emptys words before adding any
}
I want to create a function that takes a string parameter, reverses it and returns the reversed string. There have been some answers, but none work fully.
Here is my code:
#include <iostream>
#include <string>
using namespace std;
string revStr(string word){
string reversed = "";
if(word.size() == 0)
{
return reversed;
}
for (int i = word.length()-1; i>=0; i--){
reversed = reversed+word[i];
}
return reversed;
}
int main(){
string strin;
cout << "enter string;" << endl;
cin>> strin;
cout << revStr(strin);
}
This works only for strings that do not contain a space. When I type in Hello World, it return olleH.
basic_string::operator>>:
2) Behaves as an FormattedInputFunction. After constructing and checking the sentry object, which may skip leading whitespace, first clears str with str.erase(), then reads characters from is and appends them to str as if by str.append(1, c), until one of the following conditions becomes true: [...]
std::isspace(c,is.getloc()) is true for the next character c in is (this whitespace character remains in the input stream).
The method you use by definition reads until a white-space, so you read only Hello into strin. You should use another method for reading like getline or stringstream.
You need to use std::getline to input strings with a space.
For reversing your std::string, consider using std::reverse from <algorithm>, although your algorithm is correct too.
Code:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string strin;
cout << "enter string;" << endl;
getline(cin,strin);
reverse(strin.begin() , strin.end() );
cout << strin;
}
See, cin halts the input at any occurrence of a space or a newline character. So, to input a string with spaces, you'd have to use cin.getline() and that can be done by using the following snippet:
string S;
cin.getline(1000,'\n');
This would take input till the newline character into string S and then we just have to reverse the string, and that can be done in two ways.
Method 1:
Using std::reverse from <algorithm> header file. This function works with all containers and takes iterators as parameters.
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
string S;
getline(cin,S);
reverse(S.begin(), S.end());
return 0;
}
Method 2:
You can create your function which swaps the characters at positions equidistant from end and start, and you get what you need in O(n) time-complexity.
#include <bits/stdc++.h>
using namespace std;
string myfunc(string S)
{
int l = 0;
int r = S.size()-1;
while(l<r)
{
swap(S[l],S[r]);
l++;
r--;
}
return S;
}
int main()
{
ios_base::sync_with_stdio(false);
string S;
getline(cin,S);
S = myfunc(S);
cout<<S;
return 0;
}
What I think is you could do fine with your revStr() but you need to get a whole line input, but using cin considers space as a delimiter, hence you get only Hello out of Hello World.
Replace cin >> strin with getline(cin,strin).
How can I write a C program that reads your first and last names and than converts them to upper-case and lower-case letters...I know how upper and lower letters but dk how to do for first and last names..any sugegstion?...
#include<iostream>
#include<string.h>
using namespace std;
int i;
char s[255];
int main()
{
cin.get(s,255,'\n');
int l=strlen(s);
for(i=0;i<l;i++)
......................................
cout<<s; cin.get();
cin.get();
return 0;
}
You can read the first and last names directly into std::string's. There is no reason to manage the buffers yourself or guess what size they will or should be. This can be done with something like this
std::string first, last;
// Read in the first and last name.
std::cin >> first >> last;
You will want to convert the string to upper/lower case based on your requirements. This can be done with std::toupper and std::tolower which are available in the C++ Standard Library. Just include <cctype> and they are available. There are several ways to do this but one easy way is to convert the entire string to lower case then convert the first character to upper case.
// set all characters to lowercase
std::transform(str.begin(), str.end(), str.begin(), std::tolower);
// Set the first character to upper case.
str[0] = static_cast<std::string::value_type>(toupper(str[0]));
Putting this all together you get something that looks a little like this
#include <iostream>
#include <string>
#include <cctype>
void capitalize(std::string& str)
{
// only convert if the string is not empty
if (str.size())
{
// set all characters to lowercase
std::transform(str.begin(), str.end(), str.begin(), std::tolower);
// Set the first character to upper case.
str[0] = static_cast<std::string::value_type>(toupper(str[0]));
}
}
int main()
{
std::string first, last;
// Read in the first and last name.
std::cin >> first >> last;
// let's capialize them.
capitalize(first);
capitalize(last);
// Send them to the console!
std::cout << first << " " << last << std::endl;
}
Note: Including statements like using namespace std; is considered bad form as it pulls everything from the std namespace into the current scope. Avoid is as much as possible. If your professor/teacher/instructor uses it they should be chastised and forced to watch the movie Hackers until the end of time.
Since you are using C++, you should use std::string instead of a char array, and getline() does exactly what you want.
#include <iostream>
#include <string>
int main()
{
std::string first, last;
while (std::getline(cin, first, ' '))
{
std::getline(cin, last);
//Convert to upper, lower, whatever
}
}
You can leave out the loop if you only want it to get one set of input per run. The third parameter of getline() is a delimiter, which will tell the function to stop reading at when it reaches that character. It is \n by default, so you don't need to include it if you want to read the rest of the line.
I've been doing programming challenges on coderbyte and while doing one, ran into an issue. I want to isolate a word from a string, do some checks on it and then move to another word. The code I'm going to post is supposed to take only the first word and print it out on the screen. When I run it, it doesn't print anything. I thought that maybe I did something wrong in the while loop so I did a simple test. Let's say my input is "This is a test sentence" and instead of word (in cout), I type word[0]. Then it prints "T" just fine. Can you find what the problem is?
#include <iostream>
#include <string>
using namespace std;
int Letters(string str) {
int i=0;
int len=str.length();
string word;
while(i<len){
if(isspace(str[i])){word[i]='\0'; break;}
word[i]=str[i];
i++;
}
cout<<word;
return 0;
}
int main() {
int test;
string str;
getline(cin, str);
test=Letters(str);
return 0;
}
string word;
is default constructed, which is empty initially. Inside while loop, you tried to do:
word[i] = str[i];
It means you tried to access memory that has not been allocated,resulting in undefined behavior.
Try:
word.append(str[i]);
You can use simpler way to get words from input in C++. It will help you to avoid errors in the future.
#include <iostream>
using namespace std;
int main()
{
string word;
while(cin >> word)
{
// "word" contains one word of input each time loop loops
cout << word << endl;
}
return 0;
}
i have a little problem on writing the string into a file,
How can i write the string into the file and able to view it as ascii text?
because i am able to do that when i set the default value for str but not when i enter a str data
Thanks.
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
fstream out("G://Test.txt");
if(!out) {
cout << "Cannot open output file.\n";
return 1;
}
char str[200];
cout << "Enter Customers data seperate by tab\n";
cin >> str;
cin.ignore();
out.write(str, strlen(str));
out.seekp(0 ,ios::end);
out.close();
return 0;
}
Please use std::string:
#include <string>
std::string str;
std::getline(cin, str);
cout << str;
I'm not sure what the exact problem in your case was, but >> only reads up to the first separator (which is whitespace); getline will read the entire line.
Just note that >> operator will read 1 word.
std::string word;
std::cin >> word; // reads one space seporated word.
// Ignores any initial space. Then read
// into 'word' all character upto (but not including)
// the first space character (the space is gone.
// Note. Space => White Space (' ', '\t', '\v' etc...)
You're working at the wrong level of abstraction. Also, there is no need to seekp to the end of the file before closing the file.
You want to read a string and write a string. As Pavel Minaev has said, this is directly supported via std::string and std::fstream:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ofstream out("G:\\Test.txt");
if(!out) {
std::cout << "Cannot open output file.\n";
return 1;
}
std::cout << "Enter Customer's data seperated by tab\n";
std::string buffer;
std::getline(std::cin, buffer);
out << buffer;
return 0;
}
If you want to write C, use C. Otherwise, take advantage of the language you're using.
I can't believe no one found the problem. The problem was that you were using strlen on a string that wasn't terminated with a null character. strlen will keep iterating until it finds a zero-byte, and an incorrect string length might be returned (or the program might crash - it's Undefined Behavior, who knows?).
The answer is to zero-initialize your string:
char str[200] = {0};
Supplying your own string as the value of str works because those in-memory strings are null-terminated.