Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
If I execute this code
#include <iostream>
using namespace std;
int main()
{
string word;
getline(cin, word);
for (char ch: word) {
if (isupper(ch))
ch=tolower(ch);
}
cout<<word<<endl;
return 0;
}
The characters don't convert to lower cases...
What could have gone wrong?
Consider this piece of code:
char a = 'x';
char b = a;
b = 'y';
What is the value of a at the end? It is 'x' because a and b are distinct objects, and modifying b has no effect on the value of a.
Same applies to your code. The loop variable:
for (char ch: word)
^^^^^^^
is a distinct object from the element of the string. Modifying that object has no effect on the string. In order to modify the string, you need to use indirection. Use a reference to char instead of a char:
for (char& ch: word)
The issue with your code snippet is that you modify the copy of each character instead of the characters within the string.
In other words, in your loop, you need to take a reference of each character:
for (char& ch: word)
Here is a quick code snippet that does what you want to achieve:
#include <iostream>
#include <string>
#include <cassert>
static bool convert_str_to_lower(std::string* word) {
if (word == nullptr) return false;
for (char& ch : *word) {
if (std::isupper(ch)) ch=std::tolower(ch);
}
return true;
}
int main() {
std::string word = "FoOBaR";
assert(convert_str_to_lower(&word));
assert(word.compare("foobar") == 0);
std::cout << "converted str: " << word << "\n";
return 0;
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 months ago.
This post was edited and submitted for review 9 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
Annotation:
In my code I have edited the string at an adneren position, this I have not had in my example.
Since here the actual error cause/problem lay I have adapted the example, see example below.
The Answer should be:
std::string.resize increases the memory size of the string to the maximum expected size.
replace inserts the entire size into str0.
A solution is to execute resize only if str1.lengh > max_len.
Original question:
I would like to insert a string (str1) into another (str0), at any position (n).
If str1 is shorter than the rest of string str0 (n -> str0.end()), the rest of str0 should remain.
For this I wanted to use the std::string::replace() function.
#include <string>
#include <stdint.h>
#include <iostream>
int main()
{
std::string str0 = "ABCDEFGHIJ";
std::string str1 = "000";
uint16_t n = 3;
str0.replace(n, str1.length(), str1);
std::cout << "TEST:" << str0 << std::endl;
return 0;
}
In my example, I expect to output "TEST: ABC000GHIJ" via cout.
However, "TEST: ABC000" is output.
Where is the problem that the string will be cutted?
Correct code example with the error cause:
#include <string>
#include <stdint.h>
#include <iostream>
#define max_len 20
int main()
{
std::string str0 = "ABDCDEF";
std::string str1 = "";
uint16_t n = 3;
std::getline(std::cin, str1);
if(!str1.empty() && str1[str1.size()-1] == '\n') {
str1.erase(str1.size()-1);
}
str1.resize(max_len);
str0.replace(n, str1.length(), str1);
std::cout << "TEST:" << str0 << std::endl;
return 0;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
#include <bits/stdc++.h>
using namespace std;
int main()
{
char *str;
gets(str);
int size = strlen(*(&str));
//How to iterate through this str which is acting like a string here
return 0;
}
//I'm trying to print each char in a new line.
Ignoring all the other problems, such as using an uninitialized pointer, using gets (it's so bad it's been removed from C and C++), including bits/stdc++.h, not using std::string and std::getline...
Using your size variable, you can use loop like this:
for(int index = 0 ; index < size ; ++index) {
std::cout << "character at index " << index << " is '" << str[index] << "'\n";
}
But note that your code will crash at gets and never get to this loop. Please find better learning material to get started with C++!
PS. To get your code to not crash, change char *str; to char str[10000];... Then that program should run and you are unlikely to accidentally cause a buffer overflow. Still, I repeat, get better learning material!
The character pointer str doesn't point to any char object and has not been initialized.
Second, the function gets has been deprecated in C++11 and removed in C++14.
A better way would be to use std::string instead as shown below:
#include <string>
#include <iostream>
int main()
{
std::string str;
//take input from user
std::getline(std::cin, str);
//print out the size of the input string
std::cout << str.size() << std::endl;
//iterate through the input string
for(char& element: str)
{
std::cout<<element<<std::endl;
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
Hello i'm from Indonesia. and i'm verry beginner on C++ programming. I have some problem when i learn about string on C++ . First i declared array of char and i want to initialize a value separately in different command. After i initialize the value my compiler say "Invalid Argument".
#include <iostream>
using namespace std;
int main() {
char Name[5];
Name = "Luke";
cout<<"Character 0 :"<<Name[0]<<endl;
cout<<"Character 1 :"<<Name[1]<<endl;
cout<<"Character 2 :"<<Name[2]<<endl;
cout<<"Character 3 :"<<Name[3]<<endl;
cout<<"Character 4 :"<<Name[4]<<endl;
return 0;
}
sorry if my english is bad :(
A character array(including a C string) can not have a new value assigned to it after it is declared.
The C++compiler interprets these assignment statements as attempts to change the address stored in the array name, not as attempts to change the contents of the array.
However you can use
char name[] = "Luke";
A char[] can't be assigned with a string with the = operator, except for on its initialization. That's why char Name[5]; Name = "Luke"; is invalid while char Name[5] = "Luke"; is.
Assigning strings to char[] can be done with strcpy() / memcpy()-like functions.
So you have two ways of action (assuming you want to work with char[]):
char Name[5] = "Luke";
char Name[5]; strcpy(Name, "Luke"); /* don't forget to #include <string.h>*/
Just for sake of education (since the other answers are on-point to answer the question), here's how I would have written your code to do nearly the same thing.
The changes demonstrate:
used a more appropriate container (a string instead of a char[])
checked for access overruns
moved "one unit of work" into its own subroutine
Code was compiled as C++17 with /usr/bin/clang++ -Weverything -Wno-c++98-compat --std=c++1z:
#include <cstddef>
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
void PrintCharAtPos(string const& s, string::size_type pos);
int main() {
auto Name = string{"Luke"};
PrintCharAtPos(Name, 0);
PrintCharAtPos(Name, 1);
PrintCharAtPos(Name, 2);
PrintCharAtPos(Name, 3);
PrintCharAtPos(Name, 4);
return EXIT_SUCCESS;
}
void PrintCharAtPos(string const& s, string::size_type pos) {
if (pos < s.length())
cout << "Character " << pos << " : " << s[pos] << endl;
else
cout << "Character " << pos << " : (out of bounds)" << endl;
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm trying to append some characters from one string to another, but I couldn't do it. I tried something like this:
std::string fooz = "fooz";
std::string foo;
int i = 0;
while(i< fooz.length()){
if(fooz[i] != 'z'){
foo.push_back(fooz[i]);
}
i++;
}
foo after the while its empty.
You're taking length from the target string, which is still empty and the while loop won't be executed at all.
Change
while(i< foo.length()){
to
while(i< fooz.length()){
The STL can help you in this kind of scenarios.
This one uses the remove algorithm which provide a range of element to erase.
#include <string>
#include <iostream>
#include <algorithm>
int main()
{
std::string str("aaazbbb");
std::cout << str << std::endl;
str.erase(std::remove(str.begin(), str.end(), 'z'), str.end());
std::cout << str << std::endl;
}
std::string fooz = "fooz";
std::string foo;
int i = 0;
int len=fooz.size();
while(i< len){
if(fooz[i] != 'z'){
foo.push_back(fooz[i]);
}
i++;
}
Don not call std::string.size() or length() in while loop.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have to write a function that goes through a string, finds any capital letters present and makes them lowercase. I decided to add a bit of code to show what letters were found and how many were found. Although on each compilation, the value of 'cnt' yields ridiculous results.
#include <iostream>
#include <vector>
using namespace std;
int upper(string s) {
int cnt;
vector<char> v{};
for (auto& i : s) {
if (isupper(i)) {
v.push_back(i);
i = tolower(i);
++cnt;
}
}
cout << "new string is '" << s << "'\n"
<< "number of capitals found is " << cnt << "\n"
<< "letters found were ";
for (auto l : v)
cout << l << " ";
return 0;
}
int main() {
string l = "This IS a TeSt";
upper(l);
}
I'm sure I must have done something wrong with the loop but whatever the problem is, I cannot find it.
The variable cnt is never initialized when used, change
int cnt;
to
int cnt = 0;
You failed to initialize the local variable cnt. Using an uninitialized value provokes undefined behavior, under which basically anything can happen.
Use int cnt=0; and please turn on all your compiler warnings.