2

I'm totally new as a C++ programmer. I met a weird problem.

Our professor asked us to create a mergestrings function and a header file. The code part is simple and works good on my own test code. However, it cannot be compiled on TA's code.

I found it's because I didn't add using namespace std; in my header file.

Here is the header file and function.cc file:

#ifndef mergeStrings_h
#define mergeStrings_h

string mergeStrings(const string &a, const string &b);

#endif
#include <iostream>
#include <string>
using namespace std;
#include "mergeStrings.h"

string mergeStrings(const string &a, const string &b){
  int len1 = a.size(), len2 = b.size(), i=0, j=0;
  string res = "";
  while (i<len1 || j<len2){
      if (i<len1)
          res.push_back(a[i++]);
      if (j<len2)
          res.push_back(b[j++]);
  }
  return res;
};

It COULD be compiled and run on my own test code:

#include <iostream>
#include <string>
using namespace std;
#include "mergeStrings.h"

int main(){
    string a = "ace1356789";
    string b = "bdf24";
    cout<<mergeStrings(a,b)<<endl;
    return 0;
}

It COULD NOT be compiled on TA's code.

Here is part of it:

#include <iostream>
#include <string>
#include "mergeStrings.h"
using std::cout;
using std::endl;
using std::string;

const int points_per_test = 10;

void testTwoString(const string &test_name, const string &s1, const string &s2,...
      if (mergeStrings(s1, s2) == expected_string) {
        total_grade += points_for_this_test;
        cout << test_name + " succeeded! +" << points_for_this_test << endl;
    } else {
        cout << test_name + " failed!" << endl;
    }
}

int main() {...

I don't understand why it could be run on my own code.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Super Ray
  • 21
  • 3

1 Answers1

3

Your cpp files have using namespace std before #include "mergeStrings.h", so std::string has been pulled into the global namespace.

Your best option is to not write using namespace std (see Why is "using namespace std;" considered bad practice?), but instead fully qualify your types and include the necessary header.

#ifndef mergeStrings_h
#define mergeStrings_h

#include <string>

std::string mergeStrings(const std::string &a, const std::string &b);

#endif
#include <iostream>
#include <string>
#include "mergeStrings.h"

std::string mergeStrings(const std::string &a, const std::string &b){
  int len1 = a.size(), len2 = b.size(), i=0, j=0;
  std::string res = "";
  while (i<len1 || j<len2){
      if (i<len1)
          res.push_back(a[i++]);
      if (j<len2)
          res.push_back(b[j++]);
  }
  return res;
};
#include <iostream>
#include <string>
#include "mergeStrings.h"

int main(){
    std::string a = "ace1356789";
    std::string b = "bdf24";
    cout<<mergeStrings(a,b)<<endl;
    return 0;
}
Stephen Newell
  • 7,330
  • 1
  • 24
  • 28