-3

I have this block of code to output a bunch of A's to a file (500 lines of 500 A's)

int main() {
    FILE * output = fopen("somefile.txt", "w");

    //initialize string
    char s[500];
    for(int i = 0;i < 500;i++) {
        //set each letter to 'A'
        s[i] = 'A';
    }
    for(int i = 0;i < 500;i++) {
        //output the string 500 times
        fprintf(output, "%s\n", s);
    }
}

However, there's a reverse '^' at the end of each line. (screenshot here)

How do I get rid of it?

Frodakcin
  • 1
  • 3
  • 4
    C strings (yes, this is C), need to be terminated with a nul character. – Bjorn A. Aug 01 '17 at 05:05
  • You should null terminate the string of As. Use `char s[501] = {0};` – sameerkn Aug 01 '17 at 05:06
  • oh ty it worked :) – Frodakcin Aug 01 '17 at 05:07
  • @user0042: as per the selected answer of https://stackoverflow.com/questions/201101/how-to-initialize-all-members-of-an-array-to-the-same-value the c-string should automatically get null terminated. But yes for greater specificity it should be `s[i]='\0';` after the `for` loop and array should be of size `501`. Am I missing something? – sameerkn Aug 01 '17 at 05:16
  • @sameerkn Sorry, I were missing that you're proposing initialization like that. This would work, yes. – user0042 Aug 01 '17 at 05:21

1 Answers1

0

The larger problem here is that you're not using the standard library, which would trivialise your problem. Here, you should be using std::string, then you don't need to worry about memory or null-terminators or anything else:

#include <string>
int main()
{
    std::string s(500, 'A');
    for (int i = 0; i < 500; ++i)
        std::cout << s << std::endl;
}

However, the reason you're experiencing what you are is because printf requires a null-terminated string, so you'd need to write this instead:

char s[501] = {}; // default construct s so they're all null
for(int i = 0;i < 500;i++) {
    //set each letter to 'A'
    s[i] = 'A';
}
Tas
  • 7,023
  • 3
  • 36
  • 51