Thread: strings and outputs

  1. #1
    Registered User
    Join Date
    Mar 2003
    Posts
    16

    Question strings and outputs

    I'm writing code that will take a string input (any combination of
    digits, letters) and I need it to output the numbers.
    Here is the code:



    #include <iostream>
    #include <string>
    #include <cmath>

    using namespace std;

    int main()
    {
    int x,i,y;
    y = 0, x = 10;
    string did;
    cin >> did;
    for (i=0;i<13;i++)
    {
    if (isdigit(did[i]))
    {
    y = did[i];
    cout<<y<<endl;
    }
    }

    return 0;
    }

    My problem is the line y=did[i].
    I want to get y to equall the digits in the string.
    When you run it the output is some high number not the digit in the string.

  2. #2
    5|-|1+|-|34|) ober's Avatar
    Join Date
    Aug 2001
    Posts
    4,429
    as far as i know there is no "string" type in C++... you have to declare an array of characters.

    Code:
    char did[10];
    Always good to use constants in variable declarations too.

    oh, and use the code tags (see the FAQ) or hit the # symbol above your postings when making a post.

  3. #3
    Registered User
    Join Date
    Nov 2002
    Posts
    1,109
    Originally posted by ober5861
    as far as i know there is no "string" type in C++...
    <string> header file.

  4. #4
    Used Registerer jdinger's Avatar
    Join Date
    Feb 2002
    Posts
    1,065
    Try this (changes are in bold):

    Code:
    #include <iostream>
    #include <string>
    #include <cmath>
    
    using namespace std;
    
    int main()
    {
    	int x,i,y;
    	y = 0, x = 10;
    	string did;
    	cin >> did;
    	for (i=0;i<13;i++)
    	{
    		if (isdigit(did[i]))
    		{
    			y=did[i]-48;
    			cout<<y<<endl;
    		}
    	}
    	return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 04-27-2008, 03:39 AM
  2. Writing strings to file
    By Ichmael™ in forum C++ Programming
    Replies: 6
    Last Post: 07-12-2005, 12:37 PM
  3. Entering strings into a list?
    By chadsxe in forum C++ Programming
    Replies: 10
    Last Post: 06-02-2005, 12:40 PM
  4. array of strings confused me
    By linucksrox in forum C Programming
    Replies: 6
    Last Post: 05-08-2004, 09:10 PM
  5. Help w/ comparings two strings case sensitive
    By ikkin in forum C Programming
    Replies: 7
    Last Post: 11-13-2003, 08:26 AM