Cstring program not executing

Hello, Can anyone please guide what is wrong with my program. copied from a book I recently purchased and tried in code blocks. The terminal opens and I tyoe but does not give the output. I shall be grateful for help. thanks
---------------------------------------------
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
#include <cstring>

using namespace std;

int main(){
char buffer[80];
cin.getline(buffer,80,'$');
char* name[4];
name[0] = buffer;
int count = 0;
for(char* p=buffer; *p != '\0'; p++)
if(*p=='\n') { *p='\0';
name[++count] = p+1;
} cout << "names \n";
for (int i=0; i<count; i++)
cout << name[i] << endl;
}
It does, in fact, produce output. But you do not see it because the OS realizes your terminal program has terminated and gets rid of the terminal window.

You can most easily fix this by simply running the program from the terminal.


On Windows, navigate to the .exe in Explorer, click on the file path line (the “Location Bar”, analogous to the URI line in your web browser), and type cmd and press Enter. This will open a terminal window at that location.

Type dir and press Enter to see the directory (i.e. folder) contents. You will see your .exe file in the listing.

Type the name of your program to make it run. For example, if your executable is named “a.exe”, then you can type a.exe (or just a) and press Enter to make it run.

When you are done with the terminal window, either click the big red X as usual or type exit and press Enter.


On Linux it is much the same. Run the “terminal” program from the drop down menu to get the terminal window.

If your program were in your Documents ► programming ► program1 directory/folder, for example, you can change to that directory/folder by typing cd Documents/programming/program1 and pressing Enter.

To see the listing of the files in that folder, type ls and press Enter. (That’s a lower-case L and S, short for “list”.)

To run the program you must type its name. For example, if your executable is named “a.out” you must type ./a.out and press Enter to run it.

When you are done with the terminal window, either click the big X as usual or type exit and press Enter.


Another option is to add a call to an input function right at the end of main(). This is not an optimal solution. The stickied thread at the top of the Beginner’s Forum is all about ways to do this (and how inadequate they are).


Additional Notes
I do not know what book gave you that code, but it is horrible, horrible code and you should not be using it to learn. I currently recommend spending time at https://www.learncpp.com/.
Learning to program has a very steep learning curve, but many people successfully do it. It just takes a willingness to put up with a lot of frustration as you go. It eventually makes sense.

Hope this helps. :O)
Last edited on
t does, in fact, produce output. But you do not see it because the OS realizes your terminal program has terminated and gets rid of the terminal window.

You can most easily fix this by simply running the program from the terminal.

...either that, or:

Simply add a getchar() to the very end of your main() function, so that the program will wait for an input (key press) before terminating.

https://cplusplus.com/reference/cstdio/getchar/
Last edited on
Also, please use code tags so that the formatted code is readable:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
#include <cstring>

using namespace std;

int main(){
    char buffer[80];

    cin.getline(buffer,80,'$');

    char* name[4];

    name[0] = buffer;

    int count = 0;

    for (char* p = buffer; *p != '\0'; p++)
        if (*p == '\n') {
             *p = '\0';
             name[++count] = p + 1;
         }

    cout << "names \n";

    for (int i = 0; i < count; i++)
        cout << name[i] << endl;
} 


but it is horrible, horrible code and you should not be using it to learn. I currently recommend spending time at https://www.learncpp.com/.


Seconded!

Why include cstring, cstdlib, string and sstream??
Last edited on
@kigar64551
The example program posted by OP stops reading input at the $ character. There is almost certainly unread input waiting to be read after the $ (at minimum a newline character).

So... just dropping a getchar() will not be sufficient.
Last edited on
Since I thought it would be fun, here are some examples of good code to do something similar to the original code.

The major changes are:
  • Got rid of the stupid $ semaphore character.
  • Every input line is a distinct input, stored separately.
  • Sorted the inputs before displaying.


C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <algorithm>  // std::sort
#include <iostream>   // std::cin, std::cout
#include <string>     // std::string
#include <vector>     // std::vector

int main()
{
  std::vector <std::string> names;
  {
    std::cout << "Enter some names, one per line.\n"
                 "Press Enter twice to finish.\n"
                 "> ";
    std::string name;
    while (getline( std::cin, name ))
    {
      if (name.empty()) break;
      names.push_back( name );
      std::cout << "> ";
    }
  }
  
  std::sort( names.begin(), names.end() );
  
  std::cout << "Here are the names you entered, in sorted order:\n";
  for (const auto & name : names)
    std::cout << name << "\n";
}


C

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#ifdef __STDC_ALLOC_LIB__
#define __STDC_WANT_LIB_EXT2__ 1
#else
#define _POSIX_C_SOURCE 200809L
#endif

#include <stdio.h>   // printf, fflush, fgets, ...
#include <stdlib.h>  // qsort
#include <string.h>  // strchr, strdup, strcmp, ...


// Since this is C, we need some helper functions:


void scan_to_eol( FILE * f )
{
  int c;
  do c = getc( f );
  while ((c != EOF) && (c != '\n'));
}


int getline( char * s, int size_of_s, FILE * f )
// Read an entire line of text, discarding characters that don't fit in s
// Returns 1 on success, 0 on failure
{
  if (!fgets( s, size_of_s, f )) return 0;
  char * p = strchr( s, '\n' );
  if (p) *p = '\0';
  else scan_to_eol( f );
  return 1;
}


int pstrcmp( const void * a, const void * b )
{
  return strcmp( *(const char **)a, *(const char **)b );
}


int main( void )
{
  #define MAX_NAME_COUNT 1000
  char * names[ MAX_NAME_COUNT ];
  unsigned name_count = 0;
  {
    printf( "Enter some names, one per line.\n"
            "Press Enter twice to finish.\n"
            "> " );
    fflush( stdout );
    char name[ 100 ];
    while (name_count < MAX_NAME_COUNT)
    {
      if (!getline( name, sizeof(name), stdin )) break;
      if (!*name) break;
      names[ name_count++ ] = strdup( name );
      printf( "> " );
      fflush( stdout );
    }
  }
  
  qsort( names, name_count, sizeof(names[0]), pstrcmp );
  
  puts( "Here are the names you entered, in sorted order:" );
  for (unsigned n = 0;  n < name_count;  n++)
    puts( names[ n ] );
  
  return 0;
}

You see that the C main() is very similar in structure to the C++ main(), but it has significant limitations. The C code has fixed, maximum-sized inputs. We can get rid of them, but that requires yet more programming grief on our part, and a “simple” program begins getting rather wordy.

Maybe I’ll make an example C program that does that too.
As C++:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <algorithm>  // std::sort, std::copy
#include <iostream>   // std::cin, std::cout
#include <string>     // std::string
#include <vector>     // std::vector
#include <iterator>   // std::ostream_iterator

int main() {
	std::vector <std::string> names;

	std::cout << "Enter some names, one per line.\nPress Enter twice to finish.\n";

	for (std::string name; std::cout << "< " && getline(std::cin, name) && !name.empty(); names.emplace_back(std::move(name)));
	std::ranges::sort(names);

	std::cout << "Here are the names you entered, in sorted ascending order:\n";
	std::ranges::copy(names, std::ostream_iterator<std::string>(std::cout, "\n"));
}

sihaqqi wrote:
copied from a book I recently purchased

That book is likely full of horrible code if the example you posted is any indication. I'm not gonna sugar-coat the situation.

1. What is the title of this book and the year published?

2. Are you wanting to learn C or C++? If C++ you do not need to learn C first.

https://isocpp.org/blog/2014/12/five-popular-myths-about-c-bjarne-stroustrup

"To understand C++, you must first learn C" is appropriately the #1 myth.

Someone gave you an excellent online resource for learning C++l C doesn't have a free online resource like Learn C++ that I know of.

https://duckduckgo.com/?t=ffab&q=C+tutorial&atb=v188-1&ia=web

I am a C++ kinda person, so online C tutorials on that list aren't something I can say are good or bad. There are paid sites, and there are free sites on the list.

One I've looked at briefly in the past and didn't see anything really wrong right away is the C tutorial at tutorialspoint:

https://www.tutorialspoint.com/cprogramming/index.htm


Last edited on
Stay away from GeeksForGeeks.
Stay away from GeeksForGeeks.


Yeah. Some of the code is 'horrible'. Users beware...
I know more than a few GeeksForGeeks C++ code examples are big steaming piles of Amish Vehicle Exhaust. I doubt the C code examples are any better, though I can't say from personal knowledge.
Topic archived. No new replies allowed.