0

I am trying to read lines until there is an empty line and then extract first words from the lines.

on each line there is 2 words. word1 and word2. the number of lines is not known. but there is an empty line after those word lines.

example input:

word1 word2
word11 word22
word111 word222

some other text here

here is my code:

#include <iostream>
using namespace std;

int main() {
    int i;
    string line;
    string wrd1[100], wrd2[100];
    for(;getline(cin,line),!line.empty();) {
        for(i=0;i<line.size();i++) {
            if(line[i] == 32) break;
            else wrd1[i] = line[i];
        }
        cout << wrd1 << endl;
    }
    return 0;
}

but the output is in hexadecimal for some reason!

0x7fff753dad10
0x7fff753dad10
0x7fff753dad10

how do output them normally as they are (word1, word111...) and not in hexadecimal? Or why does it output in hexadecimal anyway?

OrangeBike
  • 145
  • 8
  • `but the output is in hexadecimal for some reason!` because you're outputting a pointer. – πάντα ῥεῖ Oct 07 '20 at 06:11
  • `for(;getline(cin,line),!line.empty();)` might not work the way you want. Check up on the [comma operator](https://en.cppreference.com/w/cpp/language/operator_other#Built-in_comma_operator). it looks to me like the `getline` can fail and `!line.empty()` is still used. In older C++ revisions, this is a big mistake. – user4581301 Oct 07 '20 at 06:12
  • how is it a pointer? – OrangeBike Oct 07 '20 at 06:13
  • @OrangeBike Use `std::vector wrd1(100), wrd2(100);` instead of `string wrd1[100], wrd2[100];` Note: A `std::vector` cannot be printed to `std::cout` directly, you need a loop: `for(auto word : wrd1) std::cout << word << std::endl;` – πάντα ῥεῖ Oct 07 '20 at 06:15
  • @OrangeBike _"how is it a pointer?"_ Read the duplicate please. – πάντα ῥεῖ Oct 07 '20 at 06:16

0 Answers0