• 0

[C++] Reading in first two letters of a string


Question

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

  • 0

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

  • 0

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

  • 0

Hope this isn't homework :rolleyes:

#include &lt;iostream&gt;

using namespace std;

void main()
{
	char YesNo = ' ';
	cin &gt;&gt; YesNo;
    if (YesNo == 'q')
	{
  cout &lt;&lt; "quitter";
	}
	else 
	{
	cout &lt;&lt; "whatever";
	}
}

Link to comment
Share on other sites

  • 0

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

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.