Home > Software design >  How could/should I print text strings above number columns in C ?
How could/should I print text strings above number columns in C ?

Time:01-15

I would like to print the strings at the top of columns with a 1 x 3 array.

I have edited this simple function several times and this is produces the least errors. New to C , reading Deital Chap 6 Recursive.

What am I missing? I started with half brackes around strings and brackets seemed to produce less errors. here is the code:

#include <iostream>
#include <string>
#include <array>
using namespace std;

int main() {

array a[1][3] = ["Car" "Hours" "Charge"]

cout<< a << endl;
}

Terminal produces errors as such:

parking_charges_6_12.cpp: In function ‘int main()’: parking_charges_6_12.cpp:8:7: error: missing template arguments before ‘a’ 8 | array a[1][3] = ["Car" "Hours" "Charge"] ^

CodePudding user response:

This should work:

#include <array>
#include <iostream>
#include <string>

int main(){
  std::array<std::string, 3> headlines = {"Car", "Hours", "Charge"};
  for( auto const& elem : headlines ){
    std::cout << elem << "\t";
  }
}

CodePudding user response:

It should be curly braces {} in the initializer, not []. And you need a comma between each element.

On the other hand, in later C revisions array can detect the type and number of elements, so you don't have to give that.

#include <iostream>
#include <array>
using namespace std;

int main() {

   array a = {"Car", "Hours", "Charge"};

   for (auto& item : a)
      cout<< item << endl;
}

CodePudding user response:

How about something like this:

#include<iostream>
using namespace std;
int main() {
   string data[3] = {"Car", "Hours", "Charge"};
   for (int i = 0; i < 3; i  )
      cout << data[i] << " ";
}

Obviously it is not using the array header, but it's a working example. If you do need to use the array header, you can try something like :

#include <array>
#include <iostream>
#include <iterator>
#include <string>
using namespace std;
  
int main() {
  array<string, 3> ar3 = {"Car", "Hours", "Charge"};
 
  cout << ar3.size() << endl;
    
  for (auto i : ar3)
    cout << i << ' ';
 return 0;
}

You can see it working online here

  •  Tags:  
  • Related