sir we are using ptr pointer, that is pointing to the adddress of the char .
sir suppose there is input in string and i tokenized by using strtok() function and the output of string tokenizer is the input of atoi() function to convert into string but it gives error.
please give me a suggestion what to do
I want to convert the output of string tokenizer into int
Can you send your code?
i solved the problem by using atoi but i have dout of using c_str() in atoi. please explain why we use this
this is the code #include #include #include<string.h> using namespace std; string str1[1000]; int i=0; void arr_str(string str) { string word = “”; int sum=0; for (int j=0;str[j]!=’\0’;j++) { char x=str[j]; if (x == ’ ') { sum=sum+ atoi(word.c_str()); word = “”; } else { word = word + x; } } sum=sum+ atoi(word.c_str()); cout<<sum; } int main() { string str; getline(cin,str); arr_str(str); return 0; }
What are you trying to do? what is the problem that this question is solving?
sir, i have a string. i wanted to divided by using string tokennizer function. then that string store in an array and then display the output by using that array. but storing of string gives an error and it solved by using c_str() function.
so i wanted to know about the function c_str().
Hello @Nitesh_kumar
I apologize for the delay.
I have found the mistake in your code.
The logic you have applied is correct, but the way you are initializing the string word is causing error.
The name of the string points to the first character in the string as in case of character array.
I have corrected your code. Please, check.
#include<bits/stdc++.h>
using namespace std;
string str1[1000];
int i=0;
void arr_str(string str) {
string word; //word is implicitly initialized as an empty string.
int sum=0;
for (int j=0;str[j]!=’\0’;j++) {
char x=str[j];
if (x == ’ ') {
sum=sum+ atoi(word.c_str());
word.clear(); /In your code, rather clearing the entire string, you were assigning “” to word[0] i.e. the first character./
}
else {
word = word + x;
}
}
sum=sum+ atoi(word.c_str());
cout<<sum;
}
int main() {
string str;
getline(cin,str);
arr_str(str);
return 0;
}
Hope, this would help.
Give a like if you are satisfied.
please, mark your doubt as resolved if you are satisfied.
Else, let me know.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.