Currently creating a header file, and using the ifndef, define, endif, etc to create it.
However, every time I create it, Visual Studio Code is throwing errors.
#ifndef _roundemup_h_
#define _roundemup_h_
#include <iostream>
#include <fstream>
#include <string>
void file_name(std::ifstream &input)
{
std::string filename;
while (true)
{
std::cout << "Please enter a file name: " << std::endl;
getline(std::cin, filename);
input.open(filename);
if (input.is_open())
{
break;
}
std::cerr << "Unable to Process File." << std::endl;
}
}
#endif
Current errors being show:
the #endif for this directive is missing[1,2]
unrecognized preprocessing directive[24,2]
expected a declaration[25,1]
I'm copying this from a header I've made from another program but have changed the header name and ifndef, so you would think there would be no issue?
It seems clear that the compiler is first complaining that the endif is somehow deficient. First step should be a hex dump of the file to see if there are any weird characters in there, or a missing newline.
If in Linux, you can use something like:
od -xcb myfile.h
Related
I'm currently new to C++ and I've been watching a tutorial series https://www.youtube.com/watch?v=_bYFu9mBnr4, but I'm having a big issue. My C++ code will not open a file no matter what I do, I've looked online and tried renaming it, the full path, everything I can think of. Here's my code,
#include <iostream>
#include <fstream>
#include <cstring>
#include <cerrno>
#include <filesystem>
int main()
{
std::ofstream file;
file.open("hello.txt");
if (!file.is_open())
{
std::cerr << "Error: " << strerror(errno) << '\n';
std::cout << std::filesystem::current_path() << std::endl;
}
file << "hello!";
file.close();
return 0;
}
Sorry about this question, it may have been a dumb issue. Turns out IT WAS my antivirus. Avast kept blocking it, it was just looking out for me. I decided to change my antivirus afterwards and it now works fine!
I am trying to open a text file, and the code below is my attempt:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
std::ifstream file;
file.open("InputFile.txt");
std::string fileOutput;
if (file.is_open())
{
while (!file.eof())
{
file >> fileOutput;
std::cout << fileOutput << std::endl;
}
}
else
{
std::cout << "File failed to open" << std::endl;
}
file.close();
return 0;
}
The text file is located on my desktop, and it only contain two integers.
Whenever I run the code above, it will show me the "file failed to open" message. I am completely new to c++, so I really don’t have any idea why my code is not working. So any comments would be appreciated.
The text file is located on my desktop
So where is your C++ source file, is it located in my desktop as well?
Note this code file.open("InputFile.txt"); tries to open the InputFile.txt in the current folder, that means it only works if both C++ source file and your text file are in the same folder. That seems to be your problem.
Like #ShadowRanger's this comment, the existing answers are both inaccurate. The argument for file.open() needs to either 1. reflect the relative location of the text file in relation to the current working directory (where you are calling the executable from), or 2. give the absolute location of the text file on the disc.
I suggest the following solution:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char** argv) {
if (argc != 2) {
std::cout << "incorrect number of inputs" << "\n";
std::cout << "correct usage: this_executable.exe file_location" << "\n";
return -1;
}
std::ifstream file;
file.open(argv[1]);
std::string fileOutput;
if (file.is_open())
{
while (file >> fileOutput)
{
std::cout << fileOutput << std::endl;
}
}
else
{
std::cout << "File "<< argv[1] <<" failed to open" << std::endl;
}
file.close();
return 0;
}
This solution takes the file's address info out of the code. With this solution, when you call your executable, the file's address(directory path + file name) is given to the executable at run-time rather than compile-time. Now, you'd run the executable like:
C:\path_to_your_exe>my_executable.exe C:\path_of_your_txt_file\InputFile.txt
The benefits of this approach are:
You can change the file's name / path without having to recompile the code;
On the commandline, it is easier to check that the target file's address is correct by tab completion
Also note:
As #ShadowRanger also pointed out the Why is “while ( !feof (file) )” always wrong? issue which I was not aware of.
If you are wondering what argv[1] means, see this guide for more information on commandline arguments for C++. You also want to make sure to catch situations when the user did not specify an input (meaning argv[1] is invalid, thus the argc != 2)
Unless the file you are opening and your executable are in the same directory, the same message will be printed since it will search for the file in the current working directory. You can specify the absolute path to the file on your desktop using %USERPROFILE%\\Desktop\\InputFile.txt or any other environmental variable that maps the absolute path of a disk, from which your file can be found.
i'm having trouble reading from a text file in C++, so basically I want to read the text file on "cmd" using this code, however, an error pops up.
#include <iostream>
#include <fstream>
#include <string>
using namespace::std;
int main()
{
string line_;
ifstream file("Seminario.txt");
if(file.is_open()){
while(getline(file, line_)){
cout << line_ << endl;
}
file.close();
}
else{
cout << "File is not open" << endl;
cin.get();
return 0;
}
}
When I compile it, I get no errors, however, when I run a.exe, a window pops up saying:
The procedure entry point
_ZNSt7__cxx1112basic_stringlcSt11char_traitslcESalcEEC1Ev could not be located in the dynamic link library C:\Users\pc\Desktop\Progra\a.exe.
How can I fix this?
Hi I am trying to read a Wavefront file which was created using Blender. I put a copy of this file into the solution Explorer. When I tried to compile for the first time I got the following message:
fatal error LNK1107: invalid or corrupt file: cannot read at 0x...
It seemed like the compiler confused Blender's .obj files with some other format which also uses the .obj ending. The solution was to exclude the file from the build process in its properties.
Now the application does compile but there is no data displayed like I would expect it. Not sure if this is a code issue.
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <string>
using namespace std;
void ReadPrintFile(string _fileName)
{
std::string line;
std::ifstream fileStream (_fileName);
if (fileStream.is_open())
{
while (getline(fileStream,line))
{
cout << line << '\n';
}
fileStream.close();
}
else
{
cout << "Unable to read file";
}
}
int _tmain(int argc, _TCHAR* argv[])
{
ReadPrintFile("Drone.obj");
std::cin.get();
return 0;
}
The code does not jump into the else statement. The filestream simply seems to be empty and I am directly forwarded to the cin.get(); statement. I know that there are tons of tutorials on how to parse .OBJ in C++ but I want to understand.
The trick was not to copy the file into the solution explorer but into the project folder.
Good afternoon. I've started learning c++ and I am having and issue compiling my project.
If you find some faulty code I would be glad if you tell me.
I have the following definitions:
Utils.h
#include "stdafx.h"
#include <string>
using namespace std;
class Utils
{
public:
static string GetStringFromInt (int number);
};
Utils.cpp
#include "Utils.h"
#include <sstream>
#include <string>
using namespace std;
string Utils::GetStringFromInt (int number)
{
stringstream ss;
ss << number;
return ss.str();
}
and
Ping.h
#include "stdafx.h"
#include <string>
using namespace std;
class Ping
{
public:
static int PingIt(int argc, char* argv[],string &mstime,string &ttl);
};
Ping.cpp
#include "Ping.h"
#include <string>
#include "icmpdefs.h"
#include <string>
#include <iostream>
#include <sstream>
#include <WinSock.h>
#include <Windows.h>
#include "Utils.h"
#pragma comment(lib,"wsock32.lib")
using namespace std;
int Ping::PingIt(int argc, char* argv[],string &mstime,string &ttl)
{
// Check for correct command-line args
if (argc < 2) {
cerr << "usage: ping <host>" << endl;
return 1;
}
// Load the ICMP.DLL
HINSTANCE hIcmp = LoadLibrary("ICMP.DLL");
if (hIcmp == 0) {
cerr << "Unable to locate ICMP.DLL!" << endl;
return 2;
}
// Look up an IP address for the given host name
struct hostent* phe;
if ((phe = gethostbyname(argv[1])) == 0) {
cerr << "Could not find IP address for " << argv[1] << endl;
return 3;
}
// Get handles to the functions inside ICMP.DLL that we'll need
typedef HANDLE (WINAPI* pfnHV)(VOID);
typedef BOOL (WINAPI* pfnBH)(HANDLE);
typedef DWORD (WINAPI* pfnDHDPWPipPDD)(HANDLE, DWORD, LPVOID, WORD,
PIP_OPTION_INFORMATION, LPVOID, DWORD, DWORD); // evil, no?
pfnHV pIcmpCreateFile;
pfnBH pIcmpCloseHandle;
pfnDHDPWPipPDD pIcmpSendEcho;
pIcmpCreateFile = (pfnHV)GetProcAddress(hIcmp,
"IcmpCreateFile");
pIcmpCloseHandle = (pfnBH)GetProcAddress(hIcmp,
"IcmpCloseHandle");
pIcmpSendEcho = (pfnDHDPWPipPDD)GetProcAddress(hIcmp,
"IcmpSendEcho");
if ((pIcmpCreateFile == 0) || (pIcmpCloseHandle == 0) ||
(pIcmpSendEcho == 0)) {
cerr << "Failed to get proc addr for function." << endl;
return 4;
}
// Open the ping service
HANDLE hIP = pIcmpCreateFile();
if (hIP == INVALID_HANDLE_VALUE) {
cerr << "Unable to open ping service." << endl;
return 5;
}
// Build ping packet
char acPingBuffer[64];
memset(acPingBuffer, '\xAA', sizeof(acPingBuffer));
PIP_ECHO_REPLY pIpe = (PIP_ECHO_REPLY)GlobalAlloc(
GMEM_FIXED | GMEM_ZEROINIT,
sizeof(IP_ECHO_REPLY) + sizeof(acPingBuffer));
if (pIpe == 0) {
cerr << "Failed to allocate global ping packet buffer." << endl;
return 6;
}
pIpe->Data = acPingBuffer;
pIpe->DataSize = sizeof(acPingBuffer);
// Send the ping packet
DWORD dwStatus = pIcmpSendEcho(hIP, *((DWORD*)phe->h_addr_list[0]),
acPingBuffer, sizeof(acPingBuffer), NULL, pIpe,
sizeof(IP_ECHO_REPLY) + sizeof(acPingBuffer), 5000);
if (dwStatus != 0) {
cout << "Addr: " <<
int(LOBYTE(LOWORD(pIpe->Address))) << "." <<
int(HIBYTE(LOWORD(pIpe->Address))) << "." <<
int(LOBYTE(HIWORD(pIpe->Address))) << "." <<
int(HIBYTE(HIWORD(pIpe->Address))) << ", " <<
"RTT: " << int(pIpe->RoundTripTime) << "ms, " <<
"TTL: " << int(pIpe->Options.Ttl) << endl;
mstime = Utils::GetStringFromInt((pIpe->RoundTripTime));
ttl = Utils::GetStringFromInt(int(pIpe->Options.Ttl));
}
else {
cerr << "Error obtaining info from ping packet." << endl;
}
// Shut down...
GlobalFree(pIpe);
FreeLibrary(hIcmp);
return dwStatus;
}
When I Compile the project I get:
Error 1 error C2653: 'Ping' : is not a class or namespace name c:\users\clanderasm\documents\visual studio 2010\projects\landetestconsole\landecplusconsole\ping.cpp 14 1 LandeCplusConsole
I've read sometimes this error is thrown because you dont include "stdafx.h"
on the first #include but I already changed it.
If you could tell me something more I would be glad
I couldn't reproduce your error with the code you gave, but I tried on VS2008 and some of the warning it raised make me think it could very much be due to your precompiled header not being included in sources. And there is a couple of other problems I can see that will surely cause you problems later:
Don't include precompiled header in .h. (Well you should even avoid including anything in your .h unless absolutely necessary). The precompiled header (at least in visual way of doing things) is meant to be included first in each cpp files (not .h). If you don't do so it will raise warnings for each includes you have like:
warning C4627: '#include "Ping.h"': skipped when looking for precompiled header use <- here you go your Point class is no longer defined!
and finally an error fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "stdafx.h"' to your source?.
It's actually messages I get when compiling your code on VS2008, maybe on VS2010 you have your error about Point not being defined in addition to those. When sorting out precompiled header problems it compiles fine (see next point)
Using a precompiled header does not mean the .h used to build it will be automatically included in all your sources. To do so, you have to change some project setting: right click on your project -> Properties, in the left panel, expand Configuration Properties -> C/C++ -> Advanced. Here on the list on the right you should see Force Includes. Type here stdafx.h, and voilà, you won't have to put it manually in each and every new .cpp you add to your project. Beware that you have to do that for all configuration (combo box on the top written "Configuration : Active(Debug)"
Apologies, still a VS2008 screen, hope it's the same on VS2010
Guard your headers. You should put gards on your headers to avoid multiple definitions of your classes when multiple include of the same .h happens (and it will).
You can do it 2 ways: the define method, and the pragma once method.
The pragma once is not standard but compiles faster on Visual, so you can eventually mix the 2 ways.
myheader.h using pragma once:
#pragma once
class MyClass
{
//<some definitions>
};
myheader.h using defines:
#ifndef __MYHEADER_H
#define __MYHEADER_H
class MyClass
{
//<some definitions>
};
#endif
myheader.h using both:
#pragma once
#ifndef __MYHEADER_H
#define __MYHEADER_H
class MyClass
{
//<some definitions>
};
#endif
It has already been said, but avoid the use of "using" in headers because it will spread. I myself avoid the use of "using" everywhere.