Strings of a different animal...

I'm having the worst time understanding strings. For instance, if I want to read from a file "029894 23874 27695784 39089058340" then all I have to do is set up some integer pointers like so:

1
2
3
4
5
6
7
8
int *cl, column1, etc....;
c1 = (int*) malloc(N*sizeof(int));
etc....

for (i=0; i < N + 1; i++){ // If I have lots of rows of integers to read in.
   fscanf(FILETHINGYGOESHERE, "%d %d %d %d", &column1, etc....);
       c1[i] = column1;
       etc....}



c1[0] = 029894 
c2[0] = 23874 
c3[0] = 27695784 
c4[0] = 39089058340
etc....


Pretty simple to recall this info for whatever reason. Even if I have doubles to consider, it's straight forward. But dang if I know how to deal with strings the same way! Because if I set it up this way, the computer has a seizure:

1
2
3
4
5
6
7
8
char *cl, column1, etc....;
c1 = (char*) malloc(N*sizeof(char));
etc....

for (i=0; i < N + 1; i++){
   fscanf(FILETHINGYGOESHERE, "%c %c %c %c", &column1, etc....);
       c1[i] = column1;
       etc....}


Every example I read out there with strings, of course, hard wires the string into the code only to break the entire line into individual elements: "Hello world" becomes 12 different arrays, counting the "\0" string at the end. I don't want that. I don't even want the read in just to echo it back out on my screen. I want to be able to hold this data in memory for whatever I want - particularly for manipulation purposes. Surely there is a way to take "Hello" and "world" as two different arrays: c1[0] = Hello, c2[0] = world. So, how do I accomplish this with strings in C++ (not C++11 or C# or any other C, except maybe C itself)? First one to give me the right answer gets one Monopoly-money Dollar.
man scanf wrote:
Conversion specifiers
c
Matches a sequence of characters whose length is specified by the
maximum field width (default 1); no terminating null byte is added.
So you are reading just one character

To read a word In c++ you would do
1
2
std::string word;
std::cin >> word;


c1[0] = 029894
c2[0] = 23874
c3[0] = 27695784
c4[0] = 39089058340
¿what? ¿where all those arrays come from?
¿and why you only care for the first element?
Last edited on
how do I accomplish this with strings in C++

Begin by using actual C++ strings

1
2
3
4
5
6
7
8
9
10
11
12
#include <string>
#include <iostream>
#include <fstream>

int main()
{
    std::string c1, c2;
    std::ifstream FILETHINGYGOESHERE("test.txt");
    FILETHINGYGOESHERE >> c1 >> c2;
    std::cout << "c1 = " << c1 << '\n'
              << "c2 = " << c2 << '\n';
}
Topic archived. No new replies allowed.