#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
cin.ignore();
while(t--){
string s;
getline(cin,s);
int i =0;
int count =0;
while(i<s.size()){
if(s[i]!=' '){
//cout<<count<<":";
s[count++]=s[i];
}
i++;
}
s[count]='\0';
cout<<s<<endl;
}
return 0;
}
Why in the end String is not terminating with '\0'?
For Input:
2
geeks for geeks
g f g
your output is:
geeksforgeeksks
gfgg f g
To remove a character from a string, you should use erase.
See the remove-erase idiom.
std::string is not a C-style null terminated string (but you can obtain one from it). As such, inserting a null character will not terminate it. If you want to truncate a string from the end, you can simply resize() it. Otherwise, if you want to remove characters, you can erase() them.
You say you want to remove spaces. To do that with your existing code, simply replace s[count]='\0'; with s.resize(count);, eg:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
cin.ignore();
while (t--){
string s;
getline(cin, s);
int i = 0;
int count = 0;
while (i < s.size()){
if (s[i] != ' '){
//cout<<count<<":";
s[count++] = s[i];
}
i++;
}
s.resize(count);
cout << s << endl;
}
return 0;
}
However, a better way to handle this would look more like this:
#include <iostream>
#include <string>
int main()
{
int t;
std::cin >> t;
std::cin.ignore();
while (t--){
std::string s;
std::getline(cin, s);
std::string::size_type idx = 0;
while ((idx = s.find(‘ ‘, idx)) != std::string::npos){
s.erase(idx, 1);
}
std::cout << s << std::endl;
}
return 0;
}
Alternatively:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
int t;
std::cin >> t;
std::cin.ignore();
while (t--){
std::string s;
std::getline(cin, s);
std::string::iterator iter = std::remove(s.begin(), s.end(), ‘ ‘);
s.erase(iter, s.end());
std::cout << s << std::endl;
}
return 0;
}
Related
I wrote this code to detect if an input string has a space or not. Please tell what is wrong in this approach.
#include <iostream>
#include <string>
using namespace std;
int main(){
string inp;
getline(cin, inp);
for (int i = 0; i < inp.length(); i++) {
string z = to_string(inp[i]);
if (z == " ") {
cout << "space";
}
else {
i++;
}
}
}
If i enter a string with spaces, it doesn't print "space".
Since inp is an std::string, inp[i] will be a char. Since std::to_string only has overloads for arithmetic, non-char values, calling it on a char is akin to calling it on the integer representation of said char. (If you log z, you'll likely find a number printed.)
Instead, directly compare inp[i] to a space. else { i++; } is also unnecessary – you may be jumping over spaces.
for (int i = 0; i < inp.length(); i++) {
if (inp[i] == ' ') { // note single quotes for char
cout << "space";
}
}
#TrebledJ's answer explains why your code is broken and how to fix it.
Another way to handle this situation is to use std::string::find() instead:
#include <iostream>
#include <string>
int main(){
std::string inp;
std::getline(std::cin, inp);
if (inp.find(' ') != std::string::npos) {
std::cout << "space";
}
}
Alternatively, your original code tries to output "space" for each space character found. You could use find() in a loop:
#include <iostream>
#include <string>
int main(){
std::string inp;
std::getline(std::cin, inp);
std::string::size_type idx = inp.find(' ');
while (idx != std::string::npos) {
std::cout << "space at " << idx << std::endl;
idx = inp.find(' ', idx+1);
}
}
How to apply find_first_of function for char (char array). I know it can be done for a string but I want to know how to do it when I can declare only variable of type char. It doesn't work:
#include <iostream>
#include <string>
#include <Windows.h>
#include <complex>
using namespace std;
int main()
{
char str[10];
cin >> str;
if(str[10].find_first_of('z')!=string::npos)
{
cout << "nazwa: " << str[10] << endl;
}
return (0);
}
Error: "'find_first_of'must have class\struct\union";
Compiler stressed word "str" in if(**str**[10]...) -> expression must have class type.
find_first_of is a method on string. You can only use it on an object of that type:
std::string str
cin >> str;
if (str.find_first_of('z') != std::string::npos) {
// ....
}
A char array, while serving the same purpose, is not a string, so neither your cin nor your function work. To use an array instead, you'd have to do:
char str[10];
for (int i = 0; i < 10; ++i) {
cin >> str[i];
}
if (std::find(str, str + 10, 'z') != (str + 10)) {
// ....
}
#include<iostream>
using namespace std;
int main()
{
string p;
int n,i;
cin>>n;
for(i=1;i<=n;i++)
{
cin>>p;
cout<<p<<"\n";
}
return 0;
}
hiii..
i wanna take two strings and then print them one by one as in prog. but when i take n=2 and input the string "I wanna go"
it gives the output :
i
wanna
and it didn't ask me for second string.it is taking the string until it gets a whitespace.what should i do to resolve this?
You have to change the initial value of your iteration variable i in you for statement to the following one:
for(i=0;i<=n;i++)
Consider using std::getline.
std::string name;
std::getline(std::cin, name);
The above example is summarized from:
std::cin input with spaces?
Instead of operator >> you should use function std::getline. For example
#include <iostream>
#include <limits>
int main()
{
int n;
std::cin >> n;
std::cin.ignore( std::numeric_limits<std::streamsize>::max() );
// or simply std::cin.ignore();
for ( int i = 1; i <= n; i++ )
{
std::string p;
std::getline( std::cin, p );
std::cout << p << "\n";
}
return 0;
}
Ok guy i had to make a program to split elements of a string. And after that print those words.
there are some problems i am facing:
1) the array prints more than the size of the words in string i want that it should end printing as soon as last word is printed. i tried to prevent that but it always gives runtime error when i try to break at the last word.
2)is there any other efficient way to split and print ???
#include <sstream>
#include <iostream>
#include<cstdio>
#include<cstdlib>
#include <string>
using namespace std;
int main()
{
std::string line;
std::getline(cin, line);
string arr[1000];
int i = 0;
int l=line.length();
stringstream ssin(line);
while (ssin.good() && i < l)
{
ssin >> arr[i];
++i;
}
int size = sizeof(arr) / sizeof(arr[0]);
for(i = 0; i <size; i++){
cout << arr[i] << endl;
}
return 0;
}
int size = sizeof(arr) / sizeof(arr[0]);
That is a compile time value, and it's always going to be the number of elements in your array (1000). It has no idea how many strings you assigned to in your loop. You stored the number of successfully read strings (plus 1) in the i variable, so you could do this instead:
int size = i - 1;
But if it were up to me, I would just use a growable structure, like vector (#include <vector>)
std::vector<std::string> arr;
std::string temp;
while (ssin >> temp)
{
arr.push_back(temp);
}
for (auto const & str : arr)
{
std::cout << str << std::endl;
}
/* If you're stuck in the past (can't use C++11)
for (std::vector<std::string>::iterator = arr.begin(); i != arr.end(); ++i)
{
std::cout << *i << std::endl;
}
*/
For general purpose character based splitting, I would much prefer boost::split (I know you can't use it, but for future reference)
std::vector<std::string> arr;
boost::split(arr, line, boost::is_any_of(".,;!? "));
Read up on the function strtok. It is old school but very easy to use.
1) there are a couple of changes you should make to your program:
#include <sstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
std::string line("hello string world\n");
string arr[1000];
int i = 0;
stringstream ssin(line);
while (ssin.good() && i < 1000)
{
ssin >> arr[i++];
}
int size = i-1;
for(i = 0; i < size; i++){
cout << i << ": " << arr[i] << endl;
}
return 0;
}
namely, you don't want to print sizeof(arr)/sizeof(arr[0]) (i.e. 1000) elements. There is no point in the condition i < l
2) stringstream is fine if you just want to separate the single strings; if more is needed, use boost/tokenizer for splitting strings. It's modern c++, once you try it you'll never come back!
this is the best method i think no worry now
#include <sstream>
#include <iostream>
#include<cstdio>
#include<cstdlib>
#include <cstring>
#include <string>
using namespace std;
int main ()
{
std::string str;
std::getline(cin, str);
string arr[100];
int l=0,i;
char * cstr = new char [str.length()+1];
std::strcpy (cstr, str.c_str());
// cstr now contains a c-string copy of str
char * p = std::strtok (cstr,".,;!? ");
while (p!=0)
{
//std::cout << p << '\n';
arr[l++]=p;
p = strtok(NULL,".,;!? ");
}
for(i = 0; i <l; i++)
{
cout << arr[i] << endl;
}
delete[] cstr;
return 0;
}
I'm trying to split this a string with a comma as a delimeter. I put a string "Smith,Erdos,William" and it just outputs "William" but not Smith and Erdos. There must be something wrong here that I just can't see, can anyone help?
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
int main() {
int numScenarios(0);
int numPapers(0);
int numWriters(0);
std::vector<std::string> paperTitles (1);
std::vector<std::string> paperAuthors (1);
std::vector<std::string> splitAuthors (1);
std::string token;
std::string input;
std::cin >> numScenarios;
std::cin >> numPapers >> numWriters;
for (int i(0); i < numPapers; ++i) {
std::getline(std::cin,input);
std::istringstream iss(input);
while(getline(iss,token,','));
{
std::cout << token << std::endl;
}
//paperTitles.push_back(input);
//input = '\0';
}
for (int i(0); i < numWriters; ++i) {
getline(std::cin,input);
paperAuthors.push_back(input);
input = '\0';
}
return 0;
}
while(getline(iss,token,',')); // <== look closely