I'm converting a string to char array and than back to a string and into a vector.
When I'm trying to print I'm getting this:
this
is
the
sentence iuִִ[nu#h?(h????X
and much more. This is the code:
int main(int argc, char *argv[]){
string s ="this is the sentence";
char seq[sizeof(s)];
strcpy(seq, "this is the sentence");
vector<string> vec = split(seq);
printWords(vec);
return 0;
}
And this is the func.cpp file. One function splits the char to string vector, the other is printing:
vector<string> split(char sentence[]){
vector<string> vecto;
int i=0;
int size= strlen(sentence);
while((unsigned)i< size){
string s;
char c =' ';
while(sentence[i]!=c){
s=s+sentence[i];
i+=1;
}
vecto.push_back(s);
i+=1;
}
return vecto;
}
void printWords(vector<string> words){
int i=0;
while ((unsigned)i<words.size()){
string s = words.at(i);
cout << words.at(i) << endl;
i+=1;
}
}
After understanding the answer above, try a less error-prone style, something more like this (C++11):
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main(){
string s{"this is the sentence"};
stringstream sStream;
sStream<<s;
string word;
vector<string> vec;
while(sStream >> word){
vec.emplace_back(word);
}
for(auto &w : vec){
cout << "a word: " << w <<endl;
}
}
One of your issues is that sizeof(s) != s.size().
Try this:
char letters = new char[s.size() + 1]; // +1 for the null terminator.
The expression sizeof(s) returns the size of the std::string object, not the quantity of characters in the string. The std::string object may be more than the string contents.
Also, try using std::string::operator[] to access individual characters in the string.
Example:
string s = "this is it";
char c = s[5]; // returns 'i' from "is".
You should also consider using the search functions of std::string, such as std::string::find_first_of.
Example:
unsigned int position = s.find_first_of(' ');
Another useful function is the substr method:
std::string word = s.substr(0, position);
Related
So guys, Actually What I wanna do here is that when I input 3,12,36 the output will be:
3
12
36
But here I have difficulty on how to make it output all the answer. What I have been doing is that when you input 3,12,36 it will output 3 12 only and if you type 3,12,36,48 it will output 3 12 36.
So it will always miss the last integer because my while loop is not correct I guess. but if I change it into
while(output >> life|| output >> ch)
It doesn't work either. I've done a lot of research but it still makes me confused and I'm still stuck on this part.
vector<int> parseInts(string str) {//23,4,56
vector<int>lifeishard;
stringstream output;
string lifeisgood = str;
output.str(lifeisgood);
int life;
char ch;
while(output >> life >> ch){
lifeishard.push_back(life);
//lifeishard.push_back(life2);
//lifeishard.push_back(life3);
}
return lifeishard;
}
int main() {
string str;
cin >> str;
vector<int> integers = parseInts(str);
for(int i = 0; i < integers.size(); i++) {
cout << integers[i] << "\n";
}
return 0;
}
On your last number, the while loop fails because there's no character at the end. Just the end of the string. So it doesn't execute the push_back inside the loop.
Change it so that the while loop just gets the number. Then do the push_back in the loop. Then in the loop, after the push, get the comma character. Don't bother checking for failure getting the comma because when it goes around the while loop again it will fail and exit.
I changed to using getline in your main. I changed your loop index to size_t because it is never a good idea to mix signed and unsigned integers, and whenever you use a size() function, it's a size_t. When posting your program it really should include everything. My fixed up version of your program:
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
vector<int> parseInts(string str) {//23,4,56
vector<int>lifeishard;
stringstream output;
string lifeisgood = str;
output.str(lifeisgood);
int life;
char ch;
while(output >> life){
lifeishard.push_back(life);
output >> ch;
}
return lifeishard;
}
int main() {
string str;
getline(cin, str);
vector<int> integers = parseInts(str);
for(size_t i = 0; i < integers.size(); i++) {
cout << integers[i] << "\n";
}
// Here is how we do for loops over containers in modern C++
for(auto x: integers) {
cout << x << '\n';
}
return 0;
}
A combination of stringstream, getline with delimiter and stoi would be enough for the conversion:
From the C++ reference for getline with delimiter:
Extracts characters from is and stores them into str until the delimitation character delim is found.
With this in mind, the code example below assumes the input is well-formed:
Example
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
vector<int> parseInts(const string& str, const char delim = ',')
{
vector<int> parsed;
stringstream ss(str);
string s;
while (getline(ss, s, delim)) // <- stores input in s upon hitting delimiter
parsed.push_back(stoi(s)); // <-- convert string to int and add it to parsed
return parsed;
}
int main()
{
string str = "3,12,36"; // <-- change to cin if you'd like
vector<int> ints = parseInts(str);
for (auto& i : ints)
cout << i << "\n";
}
Output
3
12
36
See more: getline, stoi
As a topic says. I try to combine few chars (from array) into one string.
i tried
char test[]={'A'};
char testt[]={'a'};
string testtt= test[0]+testt[0];
But it doesn't work.
char test[]={'A'};
char testt[]={'a'};
string testtt="";
testtt+=test[0];
testtt+=testt[0];
You can either use the constructor that takes char*, length.
#include<iostream>
#include<string>
int main(){
char test[]={'A'};
char testt[]={'a','w'};
std::string testtt= std::string(&test[0], 1) + std::string(&testt[1],1);/
std::cout<<testtt<<std::endl;
return 0;
}
or constructor that takes a range:
std::string testtt= std::string(&test[0], &test[1]) + std::string(&testt[0],&testt[1]);
It will do the trick ;)
#include <sstream>
string toStr(char* tab, int length)
{
stringstream ss;
for (int i=0 ; i<length; i++)
ss << tab[i];
return ss.str();
}
if you look inside class string you'll find that it doesn't overload copy constructor to take one character parameter.
you may think that you implement your own class containing a string object:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class MyStr
{
public:
MyStr(char c){ itsString = c;}
string GetStr()const {return itsString;}
private:
string itsString;
};
int main(int argc, char* argv[])
{
char test[]={'A'};
char testt[]={'a'};
MyStr testtt = test[0] + testt[0];
cout << testtt.GetStr() << endl;
cout << endl << endl << endl;
return 0;
}
this program runs and the compiler never complains BUT the result won't be as you may think: it won't be "Aa" but just: 'ت' because in fact the above statement: string testtt= test[0]+testt[0]; is equivalent to write: cout << (char)('A' + 'a');
which means summing two characters and the result is the integer ASCII value then this value will be converted back again to charater because you are really ivoking string(char); which will result to (charater of 162)
I need to convert a string in C++ to full upper case. I've been searching for a while and found one way to do it:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string input;
cin >> input;
transform(input.begin(), input.end(), input.begin(), toupper);
cout << input;
return 0;
}
Unfortunately this did not work and I received this error message:
no matching function for call to 'transform(std::basic_string::iterator, std::basic_string::iterator, std::basic_string::iterator,
I've tried other methods that also did not work. This was the closest to working.
So what I'm asking is what I am doing wrong. Maybe my syntax is bad or I need to include something. I am not sure.
I got most of my info here:
http://www.cplusplus.com/forum/beginner/75634/
(last two posts)
You need to put a double colon before toupper:
transform(input.begin(), input.end(), input.begin(), ::toupper);
Explanation:
There are two different toupper functions:
toupper in the global namespace (accessed with ::toupper), which comes from C.
toupper in the std namespace (accessed with std::toupper) which has multiple overloads and thus cannot be simply referenced with a name only. You have to explicitly cast it to a specific function signature in order to be referenced, but the code for getting a function pointer looks ugly: static_cast<int (*)(int)>(&std::toupper)
Since you're using namespace std, when writing toupper, 2. hides 1. and is thus chosen, according to name resolution rules.
Boost string algorithms:
#include <boost/algorithm/string.hpp>
#include <string>
std::string str = "Hello World";
boost::to_upper(str);
std::string newstr = boost::to_upper_copy("Hello World");
Convert a String In C++ To Upper Case
Try this small program, straight from C++ reference
#include <iostream>
#include <algorithm>
#include <string>
#include <functional>
#include <cctype>
using namespace std;
int main()
{
string s;
cin >> s;
std::transform(s.begin(), s.end(), s.begin(), std::ptr_fun<int, int>(std::toupper));
cout << s;
return 0;
}
Live demo
You could do:
string name = "john doe"; //or just get string from user...
for(int i = 0; i < name.size(); i++) {
name.at(i) = toupper(name.at(i));
}
Uppercase to Lowercase and viceversa using BitWise operators
1.
string s = "cAPsLock";
for(char &c: s)
c = c | ' '; // similar to: c = tolower(c);
cout << s << endl; // output: capslock
string s = "cAPsLock";
for(char &c: s)
c = c & ~' '; // similar to: c = toupper(c);
cout << s << endl; // output: CAPSLOCK
PS: for more info check this link
#include <iostream>
using namespace std;
//function for converting string to upper
string stringToUpper(string oString){
for(int i = 0; i < oString.length(); i++){
oString[i] = toupper(oString[i]);
}
return oString;
}
int main()
{
//use the function to convert string. No additional variables needed.
cout << stringToUpper("Hello world!") << endl;
return 0;
}
Like leemes said, you can use toupper(int). Like this:
void ToUpper(string &str) {
for (auto beg = str.begin(); beg != str.end(); ++beg) {
*beg = toupper(*beg);
}
}
It'll through in each character from str and convert it to upper. Example:
int main()
{
string name;
cout << "Insert a name: ";
cin >> name;
ToUpper(name);
cout << "Name in upper case: " << name << endl;
}
You can also use the function from code below to convert it to Upper-case.
#include<iostream>
#include<cstring>
using namespace std;
//Function for Converting Lower-Case to Upper-Case
void fnConvertUpper(char str[], char* des)
{
int i;
char c[1 + 1];
memset(des, 0, sizeof(des)); //memset the variable before using it.
for (i = 0; i <= strlen(str); i++) {
memset(c, 0, sizeof(c));
if (str[i] >= 97 && str[i] <= 122) {
c[0] = str[i] - 32; // here we are storing the converted value into 'c' variable, hence we are memseting it inside the for loop, so before storing a new value we are clearing the old value in 'c'.
} else {
c[0] = str[i];
}
strncat(des, &c[0], 1);
}
}
int main()
{
char str[20]; //Source Variable
char des[20]; //Destination Variable
//memset the variables before using it so as to clear any values which it contains,it can also be a junk value.
memset(str, 0, sizeof(str));
memset(des, 0, sizeof(des));
cout << "Enter the String (Enter First Name) : ";
cin >> str; //getting the value from the user and storing it into Source variable.
fnConvertUpper(str, des); //Now passing the source variable(which has Lower-Case value) along with destination variable, once the function is successfully executed the destination variable will contain the value in Upper-Case
cout << "\nThe String in Uppercase = " << des << "\n"; //now print the destination variable to check the Converted Value.
}
How do I split an input string using getline(cin, input); to input the variable? I want to split it into a char array like this:
char[] = { // What goes here to make it read the input variable and split it into chars }
Is there any way to do this?
And what about y'all's new posts? Which one is best? Here is the caesar cipher code I need to modify to read the input variable and store its chars in a char array:
// Test Code ONLY
// Not A Commercial Program OR A Crypter
// THIS IS A TEXT CIPHERER
#include <windows.h>
#include <cstdlib>
#include <iostream>
#include <string.h>
#include <vector>
using namespace std;
int main()
{
string in;
string out;
char lower[25] = {a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z};
char upper[25] = {A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z};
char upcip[25] = {Z,Y,X,W,V,U,T,S,R,Q,P,O,N,M,L,K,J,I,H,G,F,E,D,C,B,A};
char locip[25] = {z,y,x,w,v,u,t,s,r,q,p,o,n,m,l,k,j,i,h,g,f,e,d,c,b,a};
cout << "Enter PlainText: ";
getline(cin, in);
// which sample goes here to read the input var char by char, then store the chars in order in a char array in your opinion?
return 0;
}
A string is already an array of chars:
for (std::string line; std::getline(std::cin, line); )
{
for (std::size_t i = 0, e = line.size(); i != e; ++i)
{
std::cout << "char[" << i << "] = '" << line[i] << "'\n";
}
}
string str;
std::getline(cin,str);
char* pArr = new char[str.size() + 1]; // add 1 for zero element which is the end of string
strcpy(pArr,str.c_str());
/*
some actions with pArr, for ex.
while(*pArr)
std::cout << *pArr; // output string on the screen
*/
// updated: release memory obtained from heap
delete [] pArr;
How do I get a part of a string in C++? I want to know what are the elements from 0 to i.
You want to use std::string::substr. Here's an example, shamelessly copied from http://www.cplusplus.com/reference/string/string/substr/
// string::substr
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str="We think in generalities, but we live in details.";
// quoting Alfred N. Whitehead
string str2, str3;
size_t pos;
str2 = str.substr (12,12); // "generalities"
pos = str.find("live"); // position of "live" in str
str3 = str.substr (pos); // get from "live" to the end
cout << str2 << ' ' << str3 << endl;
return 0;
}
You use substr, documented here:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string a;
cout << "Enter string (5 characters or more): ";
cin >> a;
if (a.size() < 5)
cout << "Too short" << endl;
else
cout << "First 5 chars are [" << a.substr(0,5) << "]" << endl;
return 0;
}
You can also then treat it as a C-style string (non-modifiable) by using c_str, documented here.
If the string is declared as an array of characters, you can use the following approach:
char str[20];
int i;
strcpy(str, "Your String");
// Now let's get the sub-string
cin >> i;
// Do some out-of-bounds validation here if you want..
str[i + 1] = 0;
cout << str;
If you mean std::string, use substr function as Will suggested.
Assuming you're using the C++ std::string class
you can do:
std::string::size_type start = 0;
std::string::size_type length = 1; //don't use int. Use size type for portability!
std::string myStr = "hello";
std::string sub = myStr.substr(start,length);
std::cout << sub; //should print h
use:
std::string sub_of_s(s.begin(), s.begin()+i);
which create a string sub_of_s which is the first i-th the element in s.