How to combine few bacis chars into one string in c++ - c++

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)

Related

How to Replace character in c++ without using library

I have prototype - int replace_char(string &, char);
I can't use library from string and ctype.h, I should write my own function.
So the task is to find in the text caharacter, which should I should replace with "*" .
example: In This is my text .
replace all t to * . Result will be - *his is my *ex*.
#include <iostream>
using namespace std;
int replace_char(string &, char);
int main ()
{
cout << ""Please insert text:"
cin >> str;
}
int replace_char(string str, char c1)
{
for (int i = 0 ; i < str.length(); i++)
{
if(str[i]==c1)
str[i]='*';
}
return str;
}
There were several errors in the code:
The function signature mismatches, the prototype is defined as std::string& but in the function definition, std::string only was used.
The program never converted the capital letter T or anything which is capital in order to convert them before comparing each letter with a single char.
The function is never used in the code.
cin >> str won't take longer texts followed by next whitespace character.
The function wants to return an integer, but actually returned type was a std::string, which is totally a misunderstanding.
The code redefined:
#include <iostream>
// taking a reference of std::string and a char
int replaceText(std::string&, char);
int main(void) {
std::string s;
int rep;
std::cout << "Enter a string: ";
std::getline(std::cin, s); // getline() to accept whitespaces
// since we're using a reference, the original variable is manipulated
int rep = replaceText(s, 't');
std::cout << "Output: " << s << std::endl;
std::cout << "Replaced number of chars: " << rep << std::endl;
return 0;
}
int replaceText(std::string& str, char c) {
size_t len = str.length();
static int count;
// changing each letter into lowercase without using any built-in functions
for (size_t i = 0; i < len; i++)
if (str[i] >= 'A' && str[i] <= 'Z')
str[i] = str[i] + 32;
// replacing the character, the main work
for (size_t i = 0; i < len; i++)
if (str[i] == c) {
str[i] = '*';
count++; // count a static variable
}
return count; // returning the overall counts
}
The program firstly takes an input from the user of type std::string and uses reference to the variable str. Now the program enters to the function code.
In the beginning, the function converts each letter to lowercase without using any library or a built-in function. Afterwards, it tries to compare each letter of the string carefully and as soon the given character matches a value containing in the string passed to the function, it replaces and counts a static variable which keeps the value save for the entire program life.
Thereafter, it simply displays the manipulated string.
It outputs something like:
Enter a string: This is a text
Output: *his is a *ex*
Replaced chars: 3
You seem to have a good start.
You need to declare str before reading input into it. Try string str;
Then you need to use your function in main. Either store its output into another string like string replaced = replace_char(str, 't');
Or put it into the output directly like cout << replace_char(str, 't') << endl;
Probably this is what you need
#include <iostream>
using namespace std;
int replace_char(string &, char);
int main ()
{
string str;
cout << "Please insert text:"
std::getline(cin, str);
int rlen = replace_text(str, 't')
cout << str << endl;
cout << "Number of replaced : " << rlen << endl;
return 0;
}
int replace_char(string str, char c1)
{
int rlen = 0;
for (int i = 0 ; i < str.length(); i++)
{
if(str[i]==c1) {
str[i]='*';
rlen++;
}
}
return rlen;
}
Given the prototype of the function, I'm guessing you need to return the number of chars replaced. This implementation should work:
#include <string>
#include <iostream>
using namespace std;
int replace_char(string &, char);
int main ()
{
cout << "Please insert text:";
string str;
getline(cin, str);
int nCharsReplaced = replace_char(str, 't');
}
int replace_char(string& str, char c1)
{
int count = 0;
for (int i = 0 ; i < str.length(); i++)
{
if(str[i]==c1)
{
str[i]='*';
count++;
}
}
return count;
}
Keep in mind there's no need to return the string, as you're passing it by reference, so the argument itself is modified.
Also, if you want the example you provided to work the replace_char functions cannot be case sensitive, since you replaced the capital 'T' with '*' too. In order to achieve that, you could implement a function that turns every char to lowercase (ideally, you would use tolower from ctype):
char to_lower_case(char c)
{
return c - ('Z' - 'z');
}
And replace the if condition with:
if (to_lower_case(str[i]) == c1)
If you don't understand how this work, take a look at how ASCII works.

How to tell stringstream to ignore null terminating character?

Is there any way to tell a stringstream to ignore a null terminating char and read a certain amount of chars anyway?
As you can see from this minimum example, even though the char array consists of 3 chars, the stringstream terminates at the second position:
#include <sstream>
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
char test[3];
test[0] = '1';
test[1] = '\0';
test[2] = '2';
stringstream ss(test);
char c;
cout << "start" << endl;
while (ss.get(c)) {
cout << c << endl;
}
if (ss.eof()) {
cout << "eof" << endl;
}
}
$ ./a.out
start
1
eof
This question is not about stringstreams. The problem is you are implicitly constructing a std::string from a const char* for that stringstream constructor argument, and doing so using the overload that expects a C-string. So, naturally, you should expect C-string-like behaviour.
Instead you can form the argument using the std::string(const char*, std::size_t) constructor, or send the data to a default-constructed stringstream using .write.
In addition to the other answer explaining the underlying problem (creating a std::string from a char*), here's one (of many) ways around the problem, using std::string_literals:
#include <iostream>
#include <string>
#include <sstream>
int main(){
using namespace std::string_literals;
const std::string str_with_null = "1\0002"s;
std::stringstream ss(str_with_null);
char c;
while (ss.get(c)) {
std::cout << static_cast<int>(c) << '\n';
}
}
When run, this should print out:
49
0
50

Convert string to char for ascii

I want to ask for word from the user and then convert the word from string to char using 'strcpy'. Then I want to determine the sum of the ascii codes for all of the letters in the word.
However, I am having difficulties. I don't understand exactly how I can do that. This is what I have been able to do so far.
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int main()
{
string word;
cout << "Enter word: ";
getline(cin, word);
/*
char w[word];
strcpy(w,word.c_str());
int ('A');
cout<<char(65);
*/
return 0;
}
The commented part is where I have been trying to do the converting. I copied the code from a worksheet. Even if it did work, I don't know how, and what it all means.
Thanks for your help.
char w[word];
strcpy(w, word.c_str());
char w[word] is incorrect. The square brackets is for the size, which must be a constant integral expression. word is of type std::string, so this makes neither logical nor practical sense. Maybe you meant it as:
char w = word;
But that still won't work because word is a string, not a character. The correct code in this case is:
char* w = new char[word.size() + 1];
That is, you allocate the memory for w using a char*. Then you use word.size() + 1 to initialize heap-allocated memory amounting to those bytes. Don't forget for the obligatory delete[] when you're finished using w:
delete[] w;
However, note that using raw pointers and explicit new is not needed in this case. Your code can easily be cleaned up into the following:
#include <numeric>
int main ()
{
std::string word;
std::getline(std::cin, word);
int sum = std::accumulate(word.begin(), word.end(), 0); /*
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */
std::cout << "The sum is: " << sum << std::endl;
}
You don't need to use strcpy() (or use a char * at all, for that matter), but this'll do your counting using a char pointer:
#include <iostream>
#include <string>
int main() {
std::string word;
std::cout << "Enter word: ";
std::cin >> word;
const char * cword = word.c_str();
int ascii_total = 0;
while ( *cword ) {
ascii_total += *cword++;
}
std::cout << "Sum of ASCII values of characters is: ";
std::cout << ascii_total << std::endl;
return 0;
}
Output:
paul#local:~/src/cpp/scratch$ ./asccount
Enter word: ABC
Sum of ASCII values of characters is: 198
paul#local:~/src/cpp/scratch$
If you really do want to use strcpy(), I'll leave it as an exercise to you to modify the above code.
Here's a better way to do it, just using std::string (and C++11, and obviously presuming your system uses the ASCII character set in the first place):
#include <iostream>
#include <string>
int main() {
std::string word;
std::cout << "Enter word: ";
std::cin >> word;
int ascii_total = 0;
for ( auto s : word ) {
ascii_total += s;
}
std::cout << "Sum of ASCII values of characters is: ";
std::cout << ascii_total << std::endl;
return 0;
}

c++ istringstream() function converting string to int raises error

I have a string of digits. I am trying to print it as an int type each single digit in the string using istringstream. It works fine if pass whole string as argument to conversion function in main but if I pass it by index, it raises error.
How to make this code work using index to print each single digit in string array as an int.
Here is my code.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int strToNum(string str)
{
istringstream ss(str);
int n;
ss>>n;
cout<<n;
}
int main()
{
string str = "123";
for(int i=0; i<str.length(); i++)
//strToNum(str); Works fine
strToNum(str[i]); //raises error
}
str[i] is a char, while the strToNum expects a string, hence the type error.
It raises error because str[i] is a char
however , strToNum(string str) excepts a string
Try this :
for(int i=0; i<str.length(); i++)
strToNum(string(1,str[i])); //Convert char to string
See here
Others have explained your error. This is how you could make it work:
strToNum( std::string(1, str[i]) );
But I'd do this instead:
for(int i=0; i<str.length(); i++)
cout << str[i] - '0';
But ask yourself if you really need this. Are you interested in the value or the representation? If the latter, just print chars.
You don't need istringstream at all.
int strToNum(char ch)
{
cout << ch;
}
Actually I use a template function to perform this task, which is a more useful way to write the function that originated this thread ( because this single function can convert a string to any type of number: int, float, double, long double ):
#include "stdafx.h"
#include <string>
#include <iostream>
#include <Windows.h>
#include <sstream>
#include <iomanip>
using namespace std;
template <typename T>
inline bool StrToNum(const std::string& sString, T &tX)
{
std::istringstream iStream(sString);
return (iStream >> tX) ? true : false;
}
void main()
{
string a="1.23456789";
double b;
bool done = StrToNum(a,b);
cout << a << endl;
cout << setprecision(10) << b << endl;
system ("pause");
}
setprecision(10) ( iomanip ) is required otherwise istringstream will hide some decimals

c++ : printing wired string

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);