2

I have a char **names array that basically stores names from a file.

This is my .txt file

Mike, Sam, Stuart
Andre, Williams, Phillips
Patels, Khan, Smith

Basically, I want to split and store the names before the , character. For example, Mike, Sam, Stuart will become...

newName[0] = Mike
newName[1] = Sam
newName[2] = Stuart

I have something like this...

for (int i=0; i<3; i++)
{
  for (int j=60, j>0; j--)
  {
     if(names[i][j] == ',')
     {
        cout << j << endl; //THIS PRINTS OUT THE POSITION. HOW CAN I STORE THE POSITION AND DO SOMETHING?
     }
  }
}

I would appreciate it if someone could help me with my code, it is in the right direction. I don't want to use any vectors classes

I have attempted to store marks of these students, however I want to add it to a double *marks[2] array.

This is my .txt file...

69.9, 56.5
29.8, 20.0
35.6, 45.0

This is my code...

char **values;
char * pch;
pch = strtok (values[i], " ,");
while (pch != NULL)
{
    sscanf(pch, "%f, %f", &marks[i][0], &marks[i][1]);
    pch = strtok (NULL, " ,");
}

I am getting random values such as 1.28277e-307 and 1.96471e+257

6
  • Why not use std::string instead of character arrays?
    – Julian
    Dec 5, 2014 at 23:17
  • double *marks[2] : pointer ??
    – BLUEPIXY
    Dec 6, 2014 at 0:28
  • @BLUEPIXY, yes I want to store the marks into the pointer array. I need some help
    – Stu User
    Dec 6, 2014 at 0:30
  • Why pointer? Why 2?
    – BLUEPIXY
    Dec 6, 2014 at 0:38
  • @BLUEPIXY to store 2 marks per array. For example, marks[0] = 69.9, 56.5 ; marks[1] = 29.8, 20.0 and marks[2] = 35.6, 45.0
    – Stu User
    Dec 6, 2014 at 0:43

4 Answers 4

3

look up the strtok command it will be very helpful to you.

This code looks for hyphen characters and prints stuff... change it to commas

#include <string.h>
#include <stdio.h>

int main()
{
   const char str[80] = "This is - www.tutorialspoint.com - website";
   const char s[2] = "-";

   char * newName[100]; /* at most 100 names */
   int iCurName = 0;


   char *token;

   /* get the first token */
   token = strtok(str, s);

   /* walk through other tokens */
   while( token != NULL ) 
   {
      printf( " %s\n", token );
      newName[iCurName] = malloc (char *) (strlen(token) + 1);
      strcpy(newName[iCurName],token);
      iCurrName ++;

      token = strtok(NULL, s);
   }

   return(0);
}
4
  • Thanks, in my case how do I store the splitted characters into a new array. For example, newName[0] = Mike, newName[1] = Sam, newName[2] = Stuart
    – Stu User
    Dec 5, 2014 at 23:00
  • changing the answer to answer your question
    – ojblass
    Dec 5, 2014 at 23:20
  • something close to that.
    – ojblass
    Dec 5, 2014 at 23:26
  • @StuUser To populate your newName array with names, you can use strcpy_s() function #include <string.h> #include <stdlib.h> int main( void ) { char string[80]; // using template versions of strcpy_s and strcat_s: strcpy_s( string, "Hello world from " ); strcat_s( string, "strcpy_s " ); strcat_s( string, "and " ); // of course we can supply the size explicitly if we want to: strcat_s( string, _countof(string), "strcat_s!" ); printf( "String = %s\n", string ); }
    – regmagik
    Dec 5, 2014 at 23:38
0

Use function strtok() to split input line into tokens; use strcpy_s() to copy each token into name buffer.

Note 1: The strtok() function replaces each separator with '\0' character, so the line variable cannot be declared with const. If your input buffer must be constant, for example if you want to use the whole line for something else, make a copy of it before calling strtok() function.

Note 2: You might want to trim space in addition to splitting your input line.

#define MAX_LINE_LENGTH 80
#define MAX_NAME_LENGTH 20
#define MAX_NAMES_PER_LINE 3

const char constInput = "Mike, Sam, Stewart";
char line[MAX_LINE_LENGTH];
strcpy_s(line, MAX_LINE_LENGTH, constInput);

char *separator = ",";

char newName[MAX_NAMES_PER_LINE][MAX_NAME_LENGTH];
int i = 0;
char *token = strtok(line, separator);
while ((i < MAX_NAMES_PER_LINE) && ((token = strtok(NULL, separator)) != NULL))
{
    strcpy_s(newName[i++], MAX_NAME_LENGTH, token);
}
6
  • What about if I wanted to store decimals? For example, {(5.6, 9.0), (4.5, 9.0), (8.9, 2.0)}?
    – Stu User
    Dec 6, 2014 at 0:17
  • To convert strings to decimals, you can use different string conversion functions, for example, atof or sscanf.
    – regmagik
    Dec 6, 2014 at 0:24
  • Thanks for the atof function. Thanks for your response, I have attempted to store some numeric values (see edited post at the top) into a double array but I am having some difficulty. Basically, for every line I want to store both values into the same array, i.e. (marks[0][0] = 56.9, marks[0][1] = 45.6), (marks[1][0] = 16.9, marks[1][1] = 15.6)
    – Stu User
    Dec 6, 2014 at 0:29
  • @StuUser, you use strtok correctly in the last code section of the edited post, however the way you parse values into marks is not right. Try sscanf(values[i], "%f, %f", &marks[i][0], &marks[i][1]); where values[i] is a line of marks, like "5.6, 9.0"
    – regmagik
    Dec 6, 2014 at 1:00
  • thanks, but I am now getting random values such as 1.28277e-307 and 1.96471e+257
    – Stu User
    Dec 6, 2014 at 1:12
0
char newName[3][60];

for (int i=0; i<3; i++){
    int r=0, c=0;
    for (int j=0; j<60; j++){
        if(names[i][j] == ',' || names[i][j] == '\0'){
            newName[r++][c] = '\0';
            c = 0;
            if(names[i][j] == '\0'){
                cout << newName[0] << '\n'
                     << newName[1] << '\n'
                     << newName[2] << '\n' << endl;
                break;
            }
            while(names[i][++j] == ' ')
                ;
            --j;
        } else {
            newName[r][c++] = names[i][j];
        }
    }
}

#include <fstream>
#include <iostream>

using namespace std;

int main() {
    ifstream inf("data.txt");
    double marks[2];
    char ch;

    while(inf.good()){
        inf >> marks[0] >> ch >> marks[1];
        cout << "mark1:"  << marks[0] << endl;
        cout << "mark2:"  << marks[1] << endl;
    }
}
5
  • What about if I wanted to store decimals? For example, {(5.6, 9.0), (4.5, 9.0), (8.9, 2.0)}?
    – Stu User
    Dec 6, 2014 at 0:16
  • @StuUser If even numbers than it is stored as a string the same. But it is seems easy to read from a file as a numeric value.
    – BLUEPIXY
    Dec 6, 2014 at 0:17
  • Thanks for your response, I have attempted to store some numeric values (see edited post at the top) into a double array but I am having some difficulty. Basically, for every line I want to store both values into the same array, i.e. (marks[0][0] = 56.9, marks[0][1] = 45.6), (marks[1][0] = 16.9, marks[1][1] = 15.6)
    – Stu User
    Dec 6, 2014 at 0:28
  • Thanks, please help me with my edited code in my question. Basically, I want to add the values to the same marks[i][0] and marks[i][1] array, but there is something with my checks.
    – Stu User
    Dec 6, 2014 at 0:51
  • @StuUser It will be on your own. I already showed sufficient sample.
    – BLUEPIXY
    Dec 6, 2014 at 0:53
0

I don't know if this function works fast enough, but here it is:

char** split_quotes(char *input, char separator = ' ', bool keep_quotes = false)
{
    if (&input && input)
    {
        size_t length = strlen(input);
        char **chunks = new char*[length];

        bool inQuotes = false;
        size_t count = 0, from = 0;

        for (size_t i = 0; i < length; i++)
        {
            if (input[i] == '"')
            {
                inQuotes = !inQuotes;
            }
            else if (input[i] == separator && !inQuotes)
            {
                size_t strlen = i - from;

                if (strlen > 0)
                {
                    if (!keep_quotes && input[from] == '"' && input[i - 1] == '"')
                    {
                        from++; strlen -= 2;
                    }

                    chunks[count] = new char[strlen + 1]();
                    strncpy(chunks[count], &input[from], strlen);
                    count++;
                }

                from = i + 1;
            }
        }

        if (from < length)
        {
            size_t strlen = length - from;

            if (!keep_quotes && input[from] == L'"' && input[length - 1] == L'"')
            {
                from++; strlen -= 2;
            }

            chunks[count] = new char[strlen + 1]();
            strncpy(chunks[count], &input[from], strlen);
            count++;
        }

        // Save chunks to result array //
        char **result = new char*[count + 1]();
        memcpy(result, chunks, sizeof(char*) * count);

        // free chunks //
        delete[] chunks;

        return result;
    }

    return NULL;
}

Usage:

wchar_t **name = split_quotes(L"Mike,Donald,\"My Angel\",Anna", L',');
if (name)
{
    while (*name++)
    { 
        std::wcout << "Person: " << *name << std::endl;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.