saiz66 Posted August 4, 2004 Share Posted August 4, 2004 How do I read in the first two letters of a string? For example, the string: R12. I want to read just the R1 and then read the third letter 2 afterwards. Thanks in advance! Link to comment Share on other sites More sharing options...
0 neofeed Posted August 4, 2004 Share Posted August 4, 2004 Howdy saiz66, Ohh well this is C. But might be it helps. You could also go for substring or alike function. #include <stdio.h> int main (int argc, char **argv) { char * a; a = "R12"; printf ("%c%c", a[0], a[1]); } kindest regards, Moritz "neofeed" Angermann Link to comment Share on other sites More sharing options...
0 Genesi Posted August 4, 2004 Share Posted August 4, 2004 I'm sure theres a cleaner more efficient way but this is off my head. The key thing to remember is that you can access elements of a string just like a char array. #include <iostream> #include <string> using namespace std; void main() { //Initialize string to sentance string one = "Hello"; //Initialize empty string string firstwo = " "; //Steps through the string twice for (int wordCT = 0; wordCT < 2; wordCT++) { //displays the firt two elements cout << one[wordCT]; //stores the first two elements firstwo += one[wordCT]; } //Displays the stored first elements. cout << endl << firstwo; Link to comment Share on other sites More sharing options...
0 saiz66 Posted August 4, 2004 Author Share Posted August 4, 2004 thanks.. how can I compare a string with a letter q? I want it to quit if the user enters "q". Link to comment Share on other sites More sharing options...
0 Genesi Posted August 4, 2004 Share Posted August 4, 2004 Hope this isn't homework :rolleyes: #include <iostream> using namespace std; void main() { char YesNo = ' '; cin >> YesNo; if (YesNo == 'q') { cout << "quitter"; } else { cout << "whatever"; } } Link to comment Share on other sites More sharing options...
0 jonovate Posted August 4, 2004 Share Posted August 4, 2004 first to letters of your string are stringname[0] and stringname[1] Link to comment Share on other sites More sharing options...
0 Schmoove Posted August 4, 2004 Share Posted August 4, 2004 Yep, a string is nothing more then an array of characters, so you can just handle it as an array. string a; a = "hello"; if(a[0] == 'h') { etc.... } Link to comment Share on other sites More sharing options...
0 saiz66 Posted August 6, 2004 Author Share Posted August 6, 2004 thanks for all the help! Link to comment Share on other sites More sharing options...
Question
saiz66
How do I read in the first two letters of a string? For example, the string: R12. I want to read just the R1 and then read the third letter 2 afterwards. Thanks in advance!
Link to comment
Share on other sites
7 answers to this question
Recommended Posts