Solved

taking substrings of a string

Posted on 2013-05-18
3
244 Views
Last Modified: 2013-05-18
Why this little code doesn't work?I want to take a string and then assign substrings to another string.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string x = "ALERT";

string y = x[0] + x[1];   
cout << y;    //PRINT AL
return 0;
}

Open in new window

0
Comment
Question by:codeBuilder
  • 2
3 Comments
 
LVL 32

Expert Comment

by:phoffric
Comment Utility
0
 
LVL 32

Accepted Solution

by:
phoffric earned 250 total points
Comment Utility
x[0] returns char, and + on char doesn't mean concatenate. It means add the two char numbers together.
0
 
LVL 86

Assisted Solution

by:jkr
jkr earned 250 total points
Comment Utility
Since phoffric has elaborated why your attempt does not work, here's what would work - and it's surprisingly close to your question title:

#include <iostream>
#include <string>
using namespace std;
int main()
{
string x = "ALERT";

string y = x.substr(0,2);   // 1st parameter is start position, 2nd is length
cout << y;    //PRINT AL
return 0;
}
                                  

Open in new window


See also http://en.cppreference.com/w/cpp/string/basic_string/substr and http://en.cppreference.com/w/cpp/string/basic_string
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now