CSV-storing different parts(with a twist)

hi. thinking this for quite a time now. any help would be appreciated.question is:

Write a program that allows a user to type in tabular data similar to a CSV file, but instead of using commas a separator, first prompt the user to enter the separator character, then let the user type in the lines of tabular data.

my code works quite a bit just can't seem to get idea to store the last part of string after the last comma eg: if string= "abc,def,ghi,jkl", only "abc def ghi" is outputted. NO "jkl".

my code so far:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  #include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    char separator;
    string input;
    int vector_size=0;
    int k=0;///for storing and keeping track of index of partial string
    vector<string> holder(0);
    cout<<"Enter stuffs with separator character: ";
    getline(cin,input,'\n');
    cout<<"Enter the character for separator: ";
    cin>>separator;
    for(int i=input.find(separator,k);i!=string::npos;i=input.find(separator,++i))
    {

        holder.push_back(input.substr(k,i-k));

        k=i+1;
        vector_size++;
    }
    for(int i=0;i<vector_size;i++)
    {
        cout<<holder[i]<<endl;
    }
}
The separator is a CSV-dialect issue and indeed can be changed. However, it is usually coupled to string enclosure.

If a valid string field can have separator characters, then you need another non-occurring marker for string boundaries. For example:
1,"Hello, Dolly"

contains number 1, separator ,, and string Hello, Dolly. The double quotes are not part of the string; they merely protect the comma of the string.

Additional dialect choice is to treat consecutive separators as one, rather than having empty fields. Common, when separator is whitespace:
   1 "Hello, Dolly"



Your problem, however is very evident with this table::
sep==,
input==
hello
world
foobar

One column, no separators. The loop ends, when there is no remaining separators. That is why you miss the last column.

You could add the last word after the loop.
Last edited on
Add this after the first loop:

holder.push_back(input.substr(k));

vector_size is useless. Use holder.size() instead.
Last edited on
@both_commenters_above thanks guys. it worked!
@coder777 didn't know that .substr could be used with one argument. thanks!
The reference documentation is your friend:
http://www.cplusplus.com/reference/string/string/substr/

The declaration of the function has: substr (size_t pos = 0, size_t len = npos)

Therefore,
1
2
3
4
5
std::string foo;

foo.substr( 7, 42 );
foo.substr( 7 ); // compiler uses foo.substr( 7, npos );
foo.substr();    // compiler uses foo.substr( 0, npos ); 
Topic archived. No new replies allowed.