What is wrong with my code? I can't compile it [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
So the objective of this program is to display the initials of a name typed in by the user. So if I type James Issac Newton, it should give me JIN. I tried compiling my code in the terminal using g++ -Wall -o name name.cpp but it wouldn't compile. What exactly am I doing wrong??
#include<iostream>
#include<string>
#include<stdio.h>
using namespace std;
int main()
{
char name[100];
gets(name);
char a,b,c;
cin>>name;
a=name[0];
int x;
for (int i=0;i<=strlen(name);i++)
{
if (name[i]==" ")
{
b=name[i+1];
x=i;
break;
}
}
for (int j=x;j<=strlen(name);j++)
{
if (name[j]==" ")
{
c=name[j+1];
}
}
cout<<a<<b<<c;
return 0;
}
Compiler error messages:
The name of my file is acro.cpp acro.cpp:
In function âint main()â:
acro.cpp:8:2: warning: âchar* gets(char*)â is deprecated (declared at /usr/include/stdio.h:638) [-Wdeprecated-declarations]
acro.cpp:8:11: warning: âchar* gets(char*)â is deprecated (declared at /usr/include/stdio.h:638) [-Wdeprecated-declarations] acro.cpp:13:29: error: âstrlenâ was not declared in this scope

Since you declared:
char name[100];
then name[i] (if i is a valid index) is a char. But " " is not a character literal, but a string; you should code
if (name[j]==' ')
BTW, you should read more about C++ (and its std::string) and consider declaring
std::string name;
and adapting the rest of your program to make that work. BTW, compile with all warnings & debug info (g++ -Wall -Wextra -g) and learn how to use the debugger (gdb)

Presumably, the compiler told you what's wrong, but you forgot to provide that information. My compiler says
‘strlen’ was not declared in this scope
because you forgot to include the header <cstring> that defines it.
Then it says
ISO C++ forbids comparison between pointer and integer
That's a bit trickier to interpret; it refers to this
if (name[i]==" ")
where you try to compare a character (which converts to an integer) with a string (which converts to a pointer). Instead, compare with another character:
if (name[i]==' ')
^ ^
Once it compiles, get rid of gets(name);. It does the same thing as cin >> name;, but is (perhaps) even more dangerous. Then consider using std::string rather than a C-style char array; that way, your program won't explode if you enter more than 100 characters.

Apart from compiler errors you have done one more mistake :-
gets(name);
char a,b,c;
cin>>name;
second cin would overide first value you have entered using gets.

Related

C++ strtok function during compile Eclipse says not declared in scope? [duplicate]

This question already has answers here:
Error in strtok split using c++
(3 answers)
Closed 2 years ago.
I am practicing some C++ but i am having trouble splitting the user input. I am using eclipse ide 2020-03, with mingw32-gcc-g++-bin 9.2.0-1. below is my code,
#include <iostream>
#include <string>
using namespace std;
int main() {
string orderbook_symbol[500000][8]; //orderid, ordertime, symbol, buy/sell, qty, price, exp time, strike
string user_order;
char * pch;
string done= "done trading";
while(user_order.compare(done) != 0) {
cin >> user_order;
pch = strtok(user_order," ");
}
}
and when i hit compile i see this error:
23:22:06 **** Incremental Build of configuration Debug for project stasd ****
Info: Internal Builder is used for build
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o "src\\stasd.o" "..\\src\\stasd.cpp"
..\src\stasd.cpp: In function 'int main()':
..\src\stasd.cpp:26:9: error: 'strtok' was not declared in this scope; did you mean 'strtol'?
26 | pch = strtok(user_order," ");
| ^~~~~~
| strtol
23:22:06 Build Failed. 1 errors, 0 warnings. (took 560ms)
I took the example here: http://www.cplusplus.com/reference/cstring/strtok/
and i don't understand why a function call is getting not in scope error.
You're including <string>, whereas strtok is part of <string.h> or <cstring>.
See
include string or string.h
for the differences between these.

Capitalize first letter of string

I am trying to capitalize the first character of a std::string, using the same method mentioned here. For example for the following program
#include <cctype>
#include <iostream>
#include <string>
int main()
{
std::string name = "foobar";
name[0] = std::toupper(name[0]);
std::cout << name;
}
I am expecting the output to be
Foobar
When I compile this online (using GCC 4.9.2) I get the correct output without any warnings. However, when I compile the same code in Visual Studio 2013, I get a warning during the assignment back from toupper
warning C4244: '=' : conversion from 'int' to 'char', possible loss of data
Is the above method valid according to the C++ standard or is the warning correct? Otherwise is this just a false warning by Visual Studio?
The warning is correct as far the types go; the type of std::toupper as defined in the standard is:
int toupper( int ch );
Mostly because it's a remnant from the dark C ages (the cctype header is a hint at that).
However, this is just a part of the story. There's another toupper residing in the locale header:
template< class charT >
charT toupper( charT ch, const locale& loc );
This one shouldn't give you any warnings. If you're not sure what locale to provide, std::locale() will give you the default one.
std::toupper comes from the C standard, not C++, and has an annoying interface in that it takes and returns an int not a char. Using static_cast<char>(std::toupper(name[0])) will suit you.
The warning is correct, compiler will implicitly cast from int to char but this might cause lost of data in some cases. To see warning under gcc you need to add -Wconversion compiler option. Which will generate:
main.cpp: In function 'int main()':
main.cpp:8:13: warning: conversion to '__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type {aka char}' from 'int' may alter its value [-Wconversion]
name[0] = std::toupper(name[0]);
^
Foobar
Why it is not present when -Wall is set, read here:
https://gcc.gnu.org/wiki/NewWconversion
Why isn't Wconversion enabled by -Wall or at least by -Wextra?
Implicit conversions are very common in C. This tied with the fact
that there is no data-flow in front-ends (see next question) results
in hard to avoid warnings for perfectly working and valid code.
Wconversion is designed for a niche of uses (security audits, porting
32 bit code to 64 bit, etc.) where the programmer is willing to accept
and workaround invalid warnings. Therefore, it shouldn't be enabled if
it is not explicitly requested.

Understanding errors in printing a Linked list in C++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I have recently worked on C, but I have started to study C++. I had a homework in to create a program that would read texts and organize data out of the imputed text. This is the last part I have left, but I don't get what's wrong with my code. This part of the problem is pretty simple, but I still don't understand what my errors are. I got used to gcc compiler which wrote mostly segmentation fault, but g++ compiler errors are different. Any tips or hints on what to pay more attention while transferring from c to c++ would be really appreciated.
This is my output errors.
-bash-3.2$ g++ -o Printfunction Printfunction.cpp
Printfunction.cpp: In function 'void Printfunction(wordList*)':
Printfunction.cpp:43: error: cannot convert 'NumberList*' to 'Numberlist*' for argument '1' to 'std::string returnlist(Numberlist*)'
Printfunction.cpp: In function 'std::string returnlist(Numberlist*)':
Printfunction.cpp:56: error: invalid use of undefined type 'struct Numberlist'
Printfunction.cpp:10: error: forward declaration of 'struct Numberlist'
Printfunction.cpp:56: error: 'to_string' was not declared in this scope
Printfunction.cpp:57: error: invalid use of undefined type 'struct Numberlist'
Printfunction.cpp:10: error: forward declaration of 'struct Numberlist'
Can you please tell me what's wrong with my code?
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
struct NumberList
{
int line;
struct Numberlist *nextPtr;
};
struct wordList
{
string word;
int Count;
NumberList lines;
struct wordList *nextPtr;
};
void Printfunction(wordList *list);
string returnlist(Numberlist *list);
int main()
{
wordList something;
something.word = "SOMETHING";
something.Count = 55555;
something.nextPtr = NULL;
Printfunction(&something);
}
void Printfunction(wordList *list)
{
int i;
i=1;
cout<<"+----+----------------------------+-------+---------------------------------+"<<endl;
cout<<"|# | WORD | COUNT | LINES |"<<endl;
cout<<"+----+----------------------------+-------+---------------------------------+"<<endl;
while(list != NULL)
{
cout<<"|"<<left<<setw(4)<<i<<"|"<<left<<setw(28)<<list->word<<"|"<<left<<setw(7)<<list->Count<<"|"<<left<<setw(33)<<returnlist(&(list->lines))<<"|"<<endl;
cout<<"+----+----------------------------+-------+---------------------------------+"<<endl;
list = list->nextPtr;
i++;
}
}
string returnlist(Numberlist *list)
{
string final;
while(list != NULL)
{
final.append(", ");
final.append(to_string(list->line));
list = list->nextPtr;
}
final.append(".");
return final;
}
The problem is that sometimes you spell it NumberList, and sometimes you spell it Numberlist.
Any tips or hints on what to pay more attention
Case matters.

Arrays with a size determined at run time, is this valid in C++?

So I was talking to my friend, helping her with a piece of code, and I always thought that arrays needed to be compile-time constants, as they are on the stack. But she said that her friend did this using this code:
#include <iostream.h>
#include <stdlib.h>
int main()
{
int value = ' ' ;
int sum = 0;
int count = 0;
cout<<"Please enter the total number of employees" <<endl;;
cin>> value;
int numbers[value];
cout<<"Now enter the employees corresponding salaries" <<endl;;
for (int k = 0; k < value; k++)
{
cin >> numbers[k];
}
}
They are using Dev-C++.
Is this code suppose to work? I assume not.
Variable-length arrays are an extension in gcc and g++ ... so this won't work in every compiler.
For more information on gcc's support for variable length arrays, you can see the documentation here.
I believe that variable length arrays are officially unsupported in C++ but certain compilers and/or language extensions implement them.
If you want a variable length array I recommend using std::vector.
You can view its reference here:
http://www.cplusplus.com/reference/stl/vector/
#include <iostream.h>
^ is not a standard header. It used to be there in pre-standard times, i.e. before 1998. It's not there in e.g. modern Visual C++.
cin>> value;
int numbers[value];
Variable Length Arrays, or VLAs, were introduced in C99, a year after C++ was standardized. So they were not part of original standard C++, and happily they were not adopted in C++11 either. Instead of such beast, use e.g. std::vector from the vector header, or some other standard library container.
g++ supports variable length arrays as a language extension. You'd better turn off such extension. E.g.,
d:\dev\test> g++ foo.cpp
d:\dev\test> g++ -pedantic -std=c++0x -Wall -O foo.cpp
foo.cpp: In function 'int main()':
foo.cpp:11: warning: ISO C++ forbids variable length array 'numbers'
foo.cpp:7: warning: unused variable 'sum'
foo.cpp:8: warning: unused variable 'count'
d:\dev\test> _
I tried compiling it using GCC 4.6, and found that the code you've posted compiled successfully. I also tried running it and found that it worked, but I don't think the code is very good.

Expected initializer before function name

#include <iostream>
#include <string>
using namespace std;
struct sotrudnik {
string name;
string speciality;
string razread;
int zarplata;
}
sotrudnik create(string n,string spec,string raz,int sal) {
sotrudnik temp;
temp.name=n;
temp.speciality=spec;
temp.razread=raz;
temp.zarplata=sal;
return temp;
}
*sotrudnik str_compare (string str1, string str2, sotrudnik sot1, sotrudnik sot2)
I try to learn C++. But when i try to compile this code with GCC-4.4.5 by using the options " g++ -Wall -c ", I get the following error:
g++ -Wall -c "lab2.cc" (in directory: /home/ion/Univer/Cpp)
lab2.cc:11: error: expected initializer before create
lab2.cc:20: error: expected constructor, destructor, or type conversion before str_compare
Compilation failed.
Both errors are tied to the function declarations. (round 11 is the declaration of function create, round 20 - of the function str_compare). Tried to google for these kinds of errors, but couldn't find examples of similar errors, as the error messages are very generic. How can I understand their meaning and how to solve them? Thank you very much for your attention.
You are missing a semicolon at the end of your 'struct' definition.
Also,
*sotrudnik
needs to be
sotrudnik*
Try adding a semi colon to the end of your structure:
struct sotrudnik {
string name;
string speciality;
string razread;
int zarplata;
} //Semi colon here