Removing number by number from a sequence of numbers to compare them

Asked

Viewed 97 times

1

My professor of algorithms and programming techniques passed an exercise in which a = "123567348" and from that I would say which numbers are even and which are prime. He said he would have to use substr(), and passed an example:

#include <stdio.h>
#include <string>
int main ()
{
int c;
char a [] = "123456789", pedaco;
for (c = 1; c <= 10 ; c++) 
pedaco = a.substr(c,1);
  return 0;
}

but returns the error:

8 12 [Error] request for Member 'substr' in 'a', which is of non-class type 'char [10]'

In the example he gave was: pedaco = substr(a,c,1); and it didn’t work either.

  • If each piece is only a letter, why not access directly with a[c] ? (and would have to start at Indice 0)

1 answer

3


It’s mixing C with C++ and I think this is the problem, it says it was directed to use substr(), only makes sense to use the string C++ native and not use the C engine to create something like a string. If it was pure C, it doesn’t exist substr(). Would Be So:

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

int main() {
    string a = "123456789";
    for (int c = 0; c < 10; c++) cout << a.substr(c, 1);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

If I didn’t need this method I could do better:

#include <iostream>
#include <string>
using namespace std;
 
int main() {
    string a = "123456789";
    for (int c = 0; c < 10; c++) cout << a[c];
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

But in C++ it would still be better:

#include <iostream>
#include <string>
using namespace std;
 
int main() {
    string a = "123456789";
    for (char& c : a) cout << c;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • I understand, but since I store this to compare the numbers, for example it has "123456789" and I only take 2 to see if it is even and cousin?

  • Your question was not about that, but to store in a variable is just to do as I was doing, I preferred to send to the console to see working.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.