Hello..i tied a lot but i am not able to get the answer..
i am writing a program in which user input the array with space as delimiter
eg-
4 3 5
2 3
so this value should be stored in array as
a[0][0]=4
a[0][1]=3
a[0][2]=5
a[1][0]=2
a[1][1]=3
a[1][2]=0
please help me in this

Recommended Answers

All 20 Replies

How are you accepting the delimiter, by ' '? or ascii character? and what is your end of line ('\n')? I mean how are you parsing the input, post the code and I may be able to help.

You could also use the stringstream class from C++. Here's a little example:

#include <iostream>
#include <string>
#include <sstream>
#define SIZE 10
using namespace std;

bool isInt(string s){ //checks if what the user inserted is an INTeger
    if (s=="" || s==" " || s == ".") return (false);
    string dash="-";
    if (s[0]==dash[0]) s.erase(0, 1);
    for (int i=0;i<(int)s.size();i++)
        if (isdigit(s[i])==0) return (false);
    return (true);
}

int main(){
    int arr[SIZE], i=0; //define your ints
    string line; //you'll need a string for splitting the token
    cout<<"Insert numbers: ";
    getline(cin, line); //get the entire line you enter from the input, with spaces
    stringstream token(line); //get a token from that line
    while(getline(token, line, ' ') && i<SIZE) //use that token to split it into smaller parts having as delimiter the "space" ' ' character
        if (isInt(line)){ //checks if it's an INTeger
            stringstream to_int(line); //gets a stringstream off that line
            to_int>>arr[i++]; //converts it into int
       }
    for (int j=0;j<i;j++) cout<<arr[j]<<" ";
    return 0;
}

And, as a quick example:

/*
 *  Insert numbers:      2 88 kk 3 k4k 5 kk 7kk l8k 9g
 *  2 88 3 5 
 */
commented: thanks +1

@mav3rick-delimiter is ' ' and end of line is "\n"

apart from stringstream ..do we have anyother way or not?

Well if you cant use a stringstream you could always stor the line in a string and then manually parse the string yourself. The atoi() function will convert a char* into the int that it represents. To get the char* you can use substr() to get the number you want and then use c_str() on the sub string to get the char*.

commented: thanks a lot +1

The atoi() function will convert a char* into the int that it represents.

Unless it doesn't represent an int, in which case you'll invoke undefined behavior. Please forget that atoi() exists, it's totally pointless because you're forced to validate the string before passing it. The safer alternative, strtol(), does that validation for you on top of also performing the conversion you want.

I Didn't know they had strtol(). I can still see cases where you have to validate the string though. If someone enters 'a' and you convert it to base 10 strtol() will return 0 since the conversion failed but you dont know if the conversion failed or if the user entered 0.

I can still see cases where you have to validate the string though. If someone enters 'a' and you convert it to base 10 strtol() will return 0 since the conversion failed but you dont know if the conversion failed or if the user entered 0.

You're only looking at the return value. If that were the case then I'd agree that strtol() is almost as useless as atoi(). However, taking into consideration the second parameter, you can completely validate and convert all at once, then just check the results to see if there were any problems:

#include <cerrno>
#include <climits>
#include <cstring>
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string line;

    while (cout << "Enter a number: ", getline(cin, line)) {
        long value;
        char *end;

        errno = 0;
        value = strtol(line.c_str(), &end, 0);

        if (end == line.c_str()) {
            cout << "Not a number\n";
        }
        else if (errno == ERANGE || value < INT_MIN || value > INT_MAX) {
            cout << "Value out of range\n";
        }
        else {
            cout << "Converted value: " << (int)value << '\n';

            if (*end) {
                cout << "Non-numeric characters detected at '" << end << "'\n";
            }
        }
    }
}

A lot of code will just pass NULL as the second argument, but that limits error checking potential. There are four cases I can think of at the moment:

  1. The end pointer is the beginning of the string, so no conversion occurred.
  2. The end pointer is not the end of the string, so a partial conversion occurred. This may or may not be an error condition.
  3. errno is set to ERANGE, so the string was outside the range of long.
  4. The returned value is outside the range of int. In cases where int and long are not the same size, that's how you validate a lesser range than strtol() accepts.

Thanks deceptikon. Brilliant example.

#include <iostream>
#include<stdio.h>
#include<conio.h>
#include<string>
using namespace std;

int main()
{
    char *b=new char[20];
    char *t;
    int n;
    string value;
    cout<<"Enter number of value";
    cin>>n;
    cout << "Enter a number: ";
        cin.ignore();
     getline(cin, value);
    char * cstr = new char [value.length()+1];
    std::strcpy (cstr, value.c_str());

    int *a=new int[value.length()];
    cout<<value.length()<<"Length "<<endl;

    for(int i=0;i<3;i++)
{
    a[i]=atoi(cstr);
    while(*cstr!=' '&&*cstr!=NULL){
    //cout<<"cstr"<<*cstr;
    *cstr++;
    }
    *cstr++;
}
    cout<<a[0]<<endl;
    cout<<a[1];
    getch();
return 0;
}

is there any better bay apart from this or i am doing correct...suppose i enter 2 values...i can make the number of entries dynamic thats not the question

  #include <iostream>
  #include <conio>
  int a[4][4],i,j;
  main()

  {
           cout<<"Enter No.\n";

           for(i=0;i<3;i++)
           {
                   for(j=0;j<3;j++)

                   {
           cin>>a[i][j];
           }
                    }
                        cout<<"Your desire Array value is place as\n";

                        for(i=0;i<3;i++)

                        {

                        for(j=0;j<3;j++)

                        {
                        cout<<"a["<<i<< "]"<<"["<<j<<"]"<<"="<<a[i][j]<<endl;

                        }
                        }

                        getch();


  }

  enjoy!...................................dear
commented: Your code fails to compile. Please learn a bit more before trying to help. -3
commented: not good +0

my code is totally correct ...because i compile and then post here!
i am using borland c++ compiler..

my code is totally correct ...because i compile and then post here!

Then your compiler is broken, because it's accepting nonexistent headers.

They really need to ban those compilers. I mean there is no <conio> header. Everything in the standard headers are in the std namespace which I dont see you using. main() returns and int and you dont even have the return type specified. global variables are a big no no. There is no reason in your code that the variables couldnt be defined inside main.

conio.h is header file that hold the screen some time when you press key after seeing output then it accept chararter and exit the program ..it is the header file that is used in borland c++ compiler..if any one compile and run my above program in broland c++ then it properly work ...but in visual studio or other tools does not compile my code........okay so please compile my above program in c++ broland compiler then share comments about my program......thanks to all

I wouldnt install a compiler that is over 15 years old on my machine. That is why we are being critical about your code. We should be able to compile it on any compiler that is at least complient with c++98.

okay so please compile my above program in c++ broland compiler

Why should I have to make my system match yours? That's stupid. Should I also install the same operating system, applications, and use identical hardware to ensure that I get the same results as you? Why not just mail your computer to anyone who needs to run your program, because that's the restriction you're putting in place with your suggestion.

I have a better idea. How about we just not bother helping you at all? That's a lot easier than acquiring the compiler you have, installing it, and then working around whatever other exceptions are involved in making your craptastic code compile without properly fixing it.

my code is totally correct ...because i compile and then post here!

Repeating this over and over again doesn't make you right.
Try it on a compiler which wasn't developed back in the day when we still used floppy-disks and you'll see that you're wrong.

If you're only using conio for pausing the console, then you can use this:

std::cin.ignore();
std::cin.get();

instead, and get yourself out of the stone ages.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.