Error c2001 newline in constant

Using Visual Studio on a Qt project (with the Qt addon), seems to always throw up an error message: error C2001: newline in constant From the following line: this->setApplicationVersion(QString(

Using Visual Studio on a Qt project (with the Qt addon), seems to always throw up an error message:

error C2001: newline in constant

From the following line:

this->setApplicationVersion(QString(BUILD_VERSION));

or whenever I use a compiler constant defined in my QMake file. BUILD_VERSION is defined in my QMake build recipe, compiling the project works successfully if I use a different IDE (even when I use the same MSVC compiler, everything works).

I imagine I’m either missing a preference in the Qt addon or inside Visual Studio, or I need to redefine my constant’s outside of my QMake files etc…

The constant is defined and picked up by Intellisense as:

#define BUILD_VERSION "0.1.0"

Found the issue is down to escaping the quotes in the constant, in Visual Studio this won’t work but it will work with Mingw, and the MSVC compiler on the command line. Defining constants without the escaping works with Visual Studio:

#define BUILD_VERSION "0.1.0"

The problem is to define the constants in the QMake file, I need to escape like:

#define BUILD_VERSION \"0.1.0\"

Is there a way to define them in the QMake file and keep them working with Visual Studio?

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C2001

Compiler Error C2001

11/04/2016

C2001

C2001

0c3a7821-d8e5-4398-ab5a-4116d46e8dda

Compiler Error C2001

newline in constant

A string constant cannot be continued on a second line unless you do the following:

  • End the first line with a backslash.

  • Close the string on the first line with a double quotation mark and open the string on the next line with another double quotation mark.

Ending the first line with n is not sufficient.

Examples

The following sample generates C2001:

// C2001.cpp
// C2001 expected
#include <stdio.h>

int main()
{
    printf_s("Hello,
             world");
    printf_s("Hello,n
             world");
}

Spaces at the beginning of the next line after a line-continuation character are included in the string constant. None of the examples shown above embed a newline character into the string constant. You can embed a newline character as shown here:

// C2001b.cpp
#include <stdio.h>

int main()
{
    printf_s("Hello,n
             world");

    printf_s("Hello,
             nworld");

    printf_s("Hello,n"
             "world");

    printf_s("Hello,"
             "nworld");

    printf_s("Hello,"
             " world");

    printf_s("Hello,
             world");
}

Содержание

  1. Compiler errors C2000 through C2099
  2. Error C2001: Newline in constant #207
  3. Comments
  4. Ошибки компилятора с C2000 по C2099
  5. Thread: VC++ not Unicode friendly? C2001: newline in constant
  6. VC++ not Unicode friendly? C2001: newline in constant
  7. Часто встречающиеся ошибки стадии компиляции

Compiler errors C2000 through C2099

The articles in this section of the documentation explain a subset of the error messages that are generated by the compiler.

The Visual Studio compilers and build tools can report many kinds of errors and warnings. After an error or warning is found, the build tools may make assumptions about code intent and attempt to continue, so that more issues can be reported at the same time. If the tools make the wrong assumption, later errors or warnings may not apply to your project. When you correct issues in your project, always start with the first error or warning that’s reported, and rebuild often. One fix may make many subsequent errors go away.

To get help on a particular diagnostic message in Visual Studio, select it in the Output window and press the F1 key. Visual Studio opens the documentation page for that error, if one exists. You can also use the search tool at the top of the page to find articles about specific errors or warnings. Or, browse the list of errors and warnings by tool and type in the table of contents on this page.

Not every Visual Studio error or warning is documented. In many cases, the diagnostic message provides all of the information that’s available. If you landed on this page when you used F1 and you think the error or warning message needs additional explanation, let us know. You can use the feedback buttons on this page to raise a documentation issue on GitHub. If you think the error or warning is wrong, or you’ve found another problem with the toolset, report a product issue on the Developer Community site. You can also send feedback and enter bugs within the IDE. In Visual Studio, go to the menu bar and choose Help > Send Feedback > Report a Problem, or submit a suggestion by using Help > Send Feedback > Send a Suggestion.

You may find additional assistance for errors and warnings in Microsoft Learn Q&A forums. Or, search for the error or warning number on the Visual Studio C++ Developer Community site. You can also search Stack Overflow to find solutions.

For links to additional help and community resources, see Visual C++ Help and Community.

Источник

Error C2001: Newline in constant #207

I get this error when trying to build the unmodified libusb_2013.sln VS2013 solution included in your releases.

Error C2001: Newline in constant

It refers to line 111 of strerror.c, which is part of the russian error message translations. I can’t get the library to build without deleting russian from the locale arrays. Not sure if there is a syntax error you missed if or if there is some unicode problems caused by the russian characters on my system.

The text was updated successfully, but these errors were encountered:

It looks like the libusb_2013.sln solution is working fine on the Continuous Integration system: https://ci.appveyor.com/project/LudovicRousseau/libusb

Maybe it is a problem on your side?

PS: I am not a Windows expert or even user.

Maybe it is a problem on your side?

Quite possibly. I wouldn’t know how to fix it though

It is caused by my system locale it seems. If I change locale to english (US) it works. But my usual locale, Japanese, results in the error. You should be able to reproduce it if you change locale to Japanese and try building the project.

The file https://github.com/libusb/libusb/blob/master/libusb/strerror.c#L111 looks like a valid UTF-8 encoded file.
It is strange the compiler complains about the Cyrillic text but not about the French accents in the section just before.

It looks like VS2013 does not handle UTF-8 correctly. Maybe you should report the problem to Microsoft.

It fails to compile on VS2015 as well.

However, I have found that it can be very easily resolved simply by putting one space at the back of the two offending strings: Lines 111 and 117.

Kindly consider my suggestion or inform me if you prefer a pull request. This should be a rather painless solution.

What is your system locale? If you use English locale, it should be okay.
For your solution, have you tested using a few different locale? Say the Japanese locale the original poster mentioned. Thanks.

I’m on the Japanese locale as well.

Hope this comment helps.

Environment: Windows 8.1 + Visual Studio 2015, with Chinese being the system locale and UTF-8 being the source code encoding.

My Visual C++ projects failed to compile with the same error, i.e. Newline in constant , upon some (not all) Chinese string literals, after migrating source encoding from CP936 (the Chinese encoding that Windows defaults to) to UTF-8 without BOM.

And they compiled without problem after explicitly telling the compiler that the source encoding is UTF-8, say, adding /source-charset:utf-8 to Additional Options in C/C++ Command Line .

Quote with my emphasis.

By default, Visual Studio detects a byte-order mark to determine if the source file is in an encoded Unicode format, for example, UTF-16 or UTF-8. If no byte-order mark is found, it assumes the source file is encoded using the current user code page, unless you specify a character set name or code page by using the /source-charset option.

Источник

Ошибки компилятора с C2000 по C2099

В статьях в этом разделе документации объясняется подмножество сообщений об ошибках, создаваемых компилятором.

Компиляторы и средства сборки Visual Studio могут сообщать о различных типах ошибок и предупреждений. После обнаружения ошибки или предупреждения средства сборки могут делать предположения о намерении кода и пытаться продолжить работу, чтобы можно было сообщать о дополнительных проблемах одновременно. Если средства делают неверное предположение, последующие ошибки или предупреждения не могут применяться к проекту. При устранении проблем в проекте всегда начинайте с первой зарегистрированной ошибки (или предупреждения) и выполняйте повторную сборку как можно чаще. Одно исправление может привести к возникновению многих последующих ошибок.

Чтобы получить справку о конкретном диагностическом сообщении в Visual Studio, выберите его в окне вывода и нажмите клавишу F1 . Visual Studio открывает страницу документации для этой ошибки, если она существует. Вы также можете использовать средство поиска в верхней части страницы, чтобы найти статьи о конкретных ошибках или предупреждениях. Кроме того, просмотрите список ошибок и предупреждений по инструменту и введите оглавление на этой странице.

Не все ошибки или предупреждения Visual Studio описаны. Во многих случаях диагностическое сообщение предоставляет все доступные сведения. Если вы приземлились на этой странице при использовании F1 и считаете, что сообщение об ошибке или предупреждении требует дополнительного объяснения, сообщите нам об этом. Кнопки обратной связи на этой странице можно использовать для создания проблемы с документацией на сайте GitHub. Если вы считаете, что ошибка или предупреждение неправы или обнаружена другая проблема с набором инструментов, сообщите о проблеме с продуктом на сайте Сообщество разработчиков. Вы также можете отправить отзыв и ввести ошибки в интегрированной среде разработки. В Visual Studio перейдите в строку меню и выберите «Отправить > отзыв справки>» или отправьте предложение с помощью отправки > отзывов > справки.

Вы можете найти дополнительную помощь по ошибкам и предупреждениям на форумах Microsoft Learn Q&A . Или найдите номер ошибки или предупреждения на сайте Сообщество разработчиков Visual Studio C++. Вы также можете выполнить поиск решений в Stack Overflow .

Ссылки на дополнительные справочные материалы и ресурсы сообщества см. в справке и сообществе Visual C++.

Источник

Thread: VC++ not Unicode friendly? C2001: newline in constant

Thread Tools
Search Thread
Display

VC++ not Unicode friendly? C2001: newline in constant

I’ve got this little bit of simple code, and it produces lots of «C2001: newline in constant» errors.

The odd thing is that the source code file is in Unicode (UTF-8) and the program is being compiled in Unicode mode (Character Set: Use Unicode Character Set). So why is it complaining?

I need to have lots of Unicode text in my project or I will be put to a great deal of additional effort. If it’s going to do this all the time I’ll be really annoyed.

Nevermind folks — I’ve found the problem.

For future reference these errors occurred because I was saving with

Unicode (UTF-8 without signature) — Codepage 65001

as soon as I switched to

Unicode (UTF-8 with signature) — Codepage 65001

they disappeared.

This is not nice behaviour on behalf of VC++, but at least it’s liveable with (until I want to support Linux ;-).

To be honest, I found unicode support is lacking in general, in all of the C++ world (though C++0x is going to fix that, at least till some extends). If you only need it to run under VC++, there may be some easy method that works. However, that would completely kill all portability.

If you need it portable, I’d advise you to do this: Pick either UTF8, UTF16 or UTF32 to store all data in. UTF32 is a lot easier, while UTF8 is generally a lot smaller, and UTF16 is in the middle (and commonly the worst of both worlds, in stead of the best).
Now, either get or make your own string class that supports this. In case of UTF32 you can just use std::string or something similar. You’ll probably also have to write some conversion routines between UTF’s (at least from/to UTF8), but if you go to the wikipedia pages the implementations of these algorithms are trivial.
Then write all the text to some format in a text file and store it using a UTF you picked (might be another as well). Read it appropriately, convert it if required, and read it into the string class.
It’s even more fun if you actually want to use it, because it is completely OS dependant. Want to show it in a Windows messagebox? That’s UTF16. Want to show it in a linux console? UTF8 (well, in my case it was). Some other linux window manager? Probably depends on which one.

All in all, a mess to use if you need it to be portable.

>> # define ARROW_N __T(‘↑’)
Two issues:
1) There’s no point is using __T(). TCHAR’s are for code that needs to support SBCS, MBCS, and Unicode at the same (depending on the build target). What you want to use is the Unicode character U+2191. So you could do something like this:

2) Don’t use extended characters within your source code. There’s no telling what you’ll get after the compiler has translated from the «source character set» to the «execution character set» — since it’s implementation defined.

Источник

Часто встречающиеся ошибки стадии компиляции

Очень часто начинающие программисты впадают в суеверный ужас, когда видят, что компилятор нашел в тексте программы ошибку, но не понимают, в чем она заключается.

А если помножить этот факт на незнание английского языка («чего там ему не нравится. ») и слабое владение синтаксисом C++ («хм, а может, тут нужна точка с запятой…»), то проблема принимает масштаб катастрофы.

Тот факт, что компилятор в силу своих ограниченных возможностей изо всех сил старается объяснить, что конкретно неверно, не спасает ситуацию. Как быть, если гуглить неохота, а спросить не у кого?

В этом посте на правах копипаста с последующим переводом, дополнениями и исправлениями приведу описание наиболее распространенных сообщений об ошибках и предупреждений компилятора. Неприятность кроется в том факте, что разные компиляторы ругаются на одинаковые ошибки по-разному, а некоторые даже не замечают то, что другие принимают за ошибку. Все зависит от совести разработчиков компилятора, даты его выпуска, и др.

В качестве компилятора возьмем g++, который, в частности, может использоваться в среде Code::Blocks. Версия gcc (куда входит g++) для ОС Windows зовется MinGW. По ходу я буду давать аналоги ошибок из лексикона русскоязычной Microsoft Visual C++.

Итак, частые ошибки:

undeclared identifier

doy.cpp: In function ‘int main()’:
doy.cpp:25: ‘DayOfYear’ undeclared (first use this function)
doy.cpp:25: (Each undeclared identifier is reported only once for each function it appears in.)
doy.cpp:25: parse error before ‘;’ token

2) Смысл
Использован идентификатор DayOfYear , но компилятор не нашел его объявления. Он не знает, что такое DayOfYear .

  • Вы забыли включить какой-то заголовочный файл ( #include. )
  • Вы где-то ошиблись в написании идентификатора (при объявлении или использовании)
  • Вы вообще забыли, что эту переменную надо объявить

Попытавшись скомпилировать это в Microsoft Visual C++, вы увидите:

error C2065: DayOfYear: необъявленный идентификатор

cout undeclared

xyz.cpp: In function ‘int main()’:
xyz.cpp:6: ‘cout’ undeclared (first use this function)
xyz.cpp:6: (Each undeclared identifier is reported only once for each function it appears in.)

2) Смысл
Суперклассика. Без комментариев.

  • Вы забыли включить
  • Вы забыли написать using namespace std;

jump to case label

switch.cpp: In function ‘int main()’:
switch.cpp:14: jump to case label
switch.cpp:11: crosses initialization of ‘int y’

2) Смысл
Смысл туманен

3) Когда бывает
Вы попытались объявить и инициализировать переменную (объект, указатель и т.п.) в метке case оператора выбора switch. Правилами C++ это запрещено.

В Microsoft Visual C++ эта ошибка зовется

error C2360: пропуск инициализации ‘y’ из-за метки ‘case’

Выход: заключите операторы этого case’а в фигурные скобки <>.

multi-line string / unterminated string

using namespace std;

вызовет бурную реакцию компилятора:

string.cpp:7:12: warning: multi-line string literals are deprecated
string.cpp: In function ‘int main()’:
string.cpp:7: ‘so’ undeclared (first use this function)
string.cpp:7: (Each undeclared identifier is reported only once for each function it appears in.)
string.cpp:7: parse error before ‘Mary’
string.cpp:8:28: warning: multi-line string literals are deprecated
string.cpp:8:28: missing terminating » character
string.cpp:7:12: possible start of unterminated string literal

2) Смысл
Компилятор думает, что мы хотим создать строковую константу с содержащимся в ней переносом строки, что-то типа

что не поддерживается языком. Также делается предположение о том, что мы, возможно, забыли поставить кавычки в конце первой строки. Собственно, так оно и есть.

3) Когда бывает
Когда не соблюдается правильное количество и положение кавычек в строковых литералах. Надо быть внимательнее.

Microsoft Visual C++ со свойственной ему детской непосредственностью, отметит, что нельзя делать переносы в строках и возмутится, где точка с запятой:

error C2001: newline в константе
error C2146: синтаксическая ошибка: отсутствие «;» перед идентификатором «cout»

comparison between signed and unsigned integer expressions

xyz.cpp: In function ‘int main()’:
xyz.cpp:54: warning: comparison between signed and unsigned integer expressions

2) Смысл
Это — предупреждение компилятора, которое говорит о том, что мы пытаемся сравнить (==, и т.д.) целочисленное выражение (может принимать положительные, отрицательные значения и 0) и беззнаковое целочисленное выражение (может быть только положительным, либо 0).

3) Когда бывает
Собственно, тогда и бывает. Напомню, что тип int по умолчанию знаковый, а некоторые функции (например, vector::size() ) возвращают unsigned int .
К примеру, следующий на первый взгляд безобидный код вызовет описываемое предупреждение:

Следует помнить, что в памяти знаковые и беззнаковые типы имеют разные внутренние представления, поэтому надо быть чертовски осторожными с указателями.

В Microsoft Visual C++ предупреждение выглядит так:

suggest parentheses around assignment used as truth value

xyz.cpp: In function `int main()’:
xyz.cpp:54: warning: suggest parentheses around assignment used as truth value

2) Смысл
Тоже классика. Компилятор предполагает (и в 99% случаев прав), что вы по ошибке включили в скобки в качестве условия для if/while/for вместо условного выражения выражение присваивания.

3) Когда бывает
Чаще всего — в if ‘ах, когда вместо «==» используется «=»

if (length = maxLength)

if (length == maxLength)

Заминка в том, что это не ошибка, т.к. в скомпилированной программе (если мы проигнорируем предупреждение) выражение присваивания (которое возвращает значение правого аргумента) во всех случаях, кроме тех, когда оно вернет 0 , будет преобразовано к true .

Источник

  1. 06-16-2009


    #1

    PaulBlay is offline


    Registered User


    VC++ not Unicode friendly? C2001: newline in constant

    I’ve got this little bit of simple code, and it produces lots of «C2001: newline in constant» errors.

    The odd thing is that the source code file is in Unicode (UTF-8) and the program is being compiled in Unicode mode (Character Set: Use Unicode Character Set). So why is it complaining?

    Code:

    #define ARROW_DOWN	138 /* 'x8A' */
    #define ARROW_LEFT	139 /* 'x8B' */
    #define ARROW_RIGHT	140 /* 'x8C' */
    #define ARROW_UP	141 /* 'x8D' */
    
    #ifdef WINDOWS
    #  define ARROW_N __T('↑')
    #  define ARROW_E __T('→')
    #  define ARROW_S __T('↓')
    #  define ARROW_W __T('←')
    #  define ARROW_NE __T('↗')
    #  define ARROW_SE __T('↘')
    #  define ARROW_SW __T('↙')
    #  define ARROW_NW __T('↖')
    #  define ARROW_WAIT __T('↻')
    
    /* Analogous to isdigit() etc in ctypes */
    #  define isarrow(c)	( 
    	(((int)c >= ARROW_DOWN) && ((int)c <= ARROW_UP)) 
    	|| (((int)c >= ARROW_W) && ((int)c <= ARROW_S)) 
    	|| (((int)c >= ARROW_NW) && ((int)c <= ARROW_SW)) 
    	|| ((int)c >= ARROW_WAIT) 
    	)
    
    #else
    
    #  define isarrow(c)	( 
    	(((int)c >= ARROW_DOWN) && ((int)c <= ARROW_UP)) 
    	)
    
    #endif /* WINDOWS */

    I need to have lots of Unicode text in my project or I will be put to a great deal of additional effort. If it’s going to do this all the time I’ll be really annoyed.


  2. 06-16-2009


    #2

    PaulBlay is offline


    Registered User


    Nevermind folks — I’ve found the problem.

    For future reference these errors occurred because I was saving with

    Unicode (UTF-8 without signature) — Codepage 65001

    as soon as I switched to

    Unicode (UTF-8 with signature) — Codepage 65001

    they disappeared.

    This is not nice behaviour on behalf of VC++, but at least it’s liveable with (until I want to support Linux ;-).


  3. 06-16-2009


    #3

    EVOEx is offline


    Registered User


    To be honest, I found unicode support is lacking in general, in all of the C++ world (though C++0x is going to fix that, at least till some extends). If you only need it to run under VC++, there may be some easy method that works. However, that would completely kill all portability.

    If you need it portable, I’d advise you to do this: Pick either UTF8, UTF16 or UTF32 to store all data in. UTF32 is a lot easier, while UTF8 is generally a lot smaller, and UTF16 is in the middle (and commonly the worst of both worlds, in stead of the best).
    Now, either get or make your own string class that supports this. In case of UTF32 you can just use std::string<uint32_t> or something similar. You’ll probably also have to write some conversion routines between UTF’s (at least from/to UTF8), but if you go to the wikipedia pages the implementations of these algorithms are trivial.
    Then write all the text to some format in a text file and store it using a UTF you picked (might be another as well). Read it appropriately, convert it if required, and read it into the string class.
    It’s even more fun if you actually want to use it, because it is completely OS dependant. Want to show it in a Windows messagebox? That’s UTF16. Want to show it in a linux console? UTF8 (well, in my case it was). Some other linux window manager? Probably depends on which one.

    All in all, a mess to use if you need it to be portable.


  4. 06-16-2009


    #4

    Codeplug is offline


    Registered User

    Codeplug's Avatar


    >> # define ARROW_N __T(‘↑’)
    Two issues:
    1) There’s no point is using __T(). TCHAR’s are for code that needs to support SBCS, MBCS, and Unicode at the same (depending on the build target). What you want to use is the Unicode character U+2191. So you could do something like this:

    Code:

    const wchar_t ARROW_N = L'u2191';

    2) Don’t use extended characters within your source code. There’s no telling what you’ll get after the compiler has translated from the «source character set» to the «execution character set» — since it’s implementation defined.

    gg


  5. 06-16-2009


    #5

    PaulBlay is offline


    Registered User


    Quote Originally Posted by Codeplug
    View Post

    >> # define ARROW_N __T(‘↑’)
    Two issues:
    1) There’s no point is using __T(). TCHAR’s are for code that needs to support SBCS, MBCS, and Unicode at the same (depending on the build target). What you want to use is the Unicode character U+2191. So you could do something like this:

    Code:

    const wchar_t ARROW_N = L'u2191';

    I’m not using __T( for it’s MBCS / SBCS functionality, I’m using it as a handy-to-remember macro name that I can redefine or search/replace at a later point.


  6. 06-16-2009


    #6

    Codeplug is offline


    Registered User

    Codeplug's Avatar


    Then I would suggest making and using your own macro. __T() has an implied purpose when used (at least when others are reading your code).

    gg


  7. 06-16-2009


    #7

    Elysia is offline


    C++まいる!Cをこわせ!


    Quote Originally Posted by PaulBlay
    View Post

    Nevermind folks — I’ve found the problem.

    For future reference these errors occurred because I was saving with

    Unicode (UTF-8 without signature) — Codepage 65001

    as soon as I switched to

    Unicode (UTF-8 with signature) — Codepage 65001

    they disappeared.

    This is not nice behaviour on behalf of VC++, but at least it’s liveable with (until I want to support Linux ;-).

    This is not nice of you.
    How is VC++ supposed to know what format the file is saved in without a signature?

    Quote Originally Posted by Adak
    View Post

    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.

    Quote Originally Posted by Salem
    View Post

    You mean it’s included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.


  8. 06-17-2009


    #8

    PaulBlay is offline


    Registered User


    Quote Originally Posted by Elysia
    View Post

    This is not nice of you.
    How is VC++ supposed to know what format the file is saved in without a signature?

    By looking at it. Visual Studio does, after all, display the file correctly in the IDE. (As set with the «Auto-detect UTF-8 encoding without signature.» option) So the left hand knows what it’s doing — it didn’t occur to me that the right hand hadn’t been informed.


AirLiss

1 / 1 / 1

Регистрация: 06.06.2014

Сообщений: 115

1

10.06.2014, 13:57. Показов 6019. Ответов 15

Метки нет (Все метки)


здравствуйте. учусь по книге Шилдта там такой пример( да и везде впринципе начинают с этого примера)

C++ (Qt)
1
2
3
4
5
6
7
8
#include "iostream>
using namespace std;
 
int main()
{
    cout <<"C++ - ýòî ñèëà";
    return 0;
}

пишутся 2 ошибки:
error C2001: newline in constant
fatal error C1010: unexpected end of file while looking for precompiled header directive

а при использовании стандартной книги и просто изменении в нем записи — ошибок нет.

C++ (Qt)
1
2
3
4
5
6
7
#include "stdafx.h"
 
int main(int argc, char* argv[])
{
    printf("C++ - very good!n");
    return 0;
}

в чем разница?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



31 / 31 / 19

Регистрация: 03.05.2011

Сообщений: 84

10.06.2014, 14:05

2

Лучший ответ Сообщение было отмечено AirLiss как решение

Решение

Опечатка у Вас. Надо <iostream>, а не «iostream>



1



42 / 42 / 18

Регистрация: 12.03.2013

Сообщений: 148

10.06.2014, 14:06

3

какую среду использушь?

Цитата
Сообщение от AirLiss
Посмотреть сообщение

#include «iostream>

одинакововые скобки поставь



1



Eva Rosalene

Pure Free Digital Ghost

4598 / 1910 / 370

Регистрация: 06.01.2013

Сообщений: 4,564

10.06.2014, 14:06

4

Надо

C++
1
#include <iostream>

, а не

C++
1
#include "iostream>



1



1 / 1 / 1

Регистрация: 06.06.2014

Сообщений: 115

10.06.2014, 14:10

 [ТС]

5

осталась одна ошибка
c:program filesmicrosoft visual studiomyprojects11.cpp(13) : fatal error C1010: unexpected end of file while looking for precompiled header directive
Error executing cl.exe.

Добавлено через 2 минуты
среда microsoft visual c++



0



Pure Free Digital Ghost

4598 / 1910 / 370

Регистрация: 06.01.2013

Сообщений: 4,564

10.06.2014, 14:16

6

Лучший ответ Сообщение было отмечено SatanaXIII как решение

Решение

AirLiss, Project-> Settings->C/C++->Category->Precompiled headers->not using precompiled headers.
Если среда нелокализована



1



1 / 1 / 1

Регистрация: 06.06.2014

Сообщений: 115

10.06.2014, 14:22

 [ТС]

7

FraidZZ спасибо огромное! помогло!

еще маааленький вопросик. когда прокомпелируешь, в папке дебаг появляется экзешник. пробую его запустить — что бы как и при компелировании выходило такое же окошко — но только мелькает окошко и исчезает.. как же например переподавателю показать что экзешниик рабочий?

Добавлено через 2 минуты
и как сделать что б мне каждый раз не локализовывать каждую программу? не проделывать этот путь: Project-> Settings->C/C++->Category->Precompiled headers->not using precompiled headers.



0



Eva Rosalene

Pure Free Digital Ghost

4598 / 1910 / 370

Регистрация: 06.01.2013

Сообщений: 4,564

10.06.2014, 14:22

8

AirLiss, добавьте, например, в конец кода (перед return)

C++
1
getch();

Тогда пока вы не нажмете [Enter], программа не завершится.



0



1 / 1 / 1

Регистрация: 06.06.2014

Сообщений: 115

10.06.2014, 14:28

 [ТС]

9

error C2065: ‘getch’ : undeclared identifier
где то читала о разных прочтениях этой строки — какие есть еще варианты? _getch(); тоже не полюбил…



0



Esecman

39 / 27 / 12

Регистрация: 31.12.2013

Сообщений: 329

10.06.2014, 14:30

10

C++
1
getchar();

Если не поможет, то воспользуйтесь одним из вариантов….

C++
1
system("PAUSE");
C++
1
cin.get();



1



2758 / 1912 / 569

Регистрация: 05.06.2014

Сообщений: 5,561

10.06.2014, 14:31

11

как же например переподавателю показать что экзешниик рабочий?

Правой кнопкой по папке, выбрать пункт «запуск командной строки здесь». В открывшейся консоли ввести имя экзешника и нажать энтер.



0



1 / 1 / 1

Регистрация: 06.06.2014

Сообщений: 115

10.06.2014, 14:36

 [ТС]

12

все три варианта рабочие, но своего не добилась — екзешник запускаю — прога мелькает и исчезает, хотя при компиляции вполне ждет когда я что-нибудь нажму…



0



3985 / 3255 / 909

Регистрация: 25.03.2012

Сообщений: 12,102

Записей в блоге: 1

10.06.2014, 14:42

13

AirLiss, ctrl+F5 в студии.
или запускай из командной строки, раз запускаешь вызовом екзешника.



0



Pure Free Digital Ghost

4598 / 1910 / 370

Регистрация: 06.01.2013

Сообщений: 4,564

10.06.2014, 14:44

14

AirLiss, запускай из командной строки. В папке с экзешником (ни один файл не должен быть выделен) Shift + Правый клик по пустому месту, там выбираешь «Открыть в командной строке» и вводишь имя экзешника.



1



1 / 1 / 1

Регистрация: 06.06.2014

Сообщений: 115

10.06.2014, 14:49

 [ТС]

15

FraidZZ, спасиббо — самый доспупный для понимания способ.

З.Ы. как понимаю, как обычный экзешник его не получится запускать, только через СМД или через саму прогу. спасибо всем за оперативные ответы — будем стараться, изучать)



0



Sh@dow777

17 / 17 / 6

Регистрация: 10.12.2013

Сообщений: 740

10.06.2014, 16:09

16

AirLiss, Да нет, вам просто нужно после

C++
1
#include <iostream>

написать

C++
1
#include <conio.h>

тогда все будет работать.

C++
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <conio.h>
using namespace std;
 
int main()
{
    cout <<"C++ - это сила";
 
    getch();
 
    return 0;
}



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

10.06.2014, 16:09

16

  • Remove From My Forums
  • Question

  • When i use this code

    #include "stdafx.h"
    #include<iostream>
    using namespace std;
    
    int main(void)
    {
    
    	system("TITLE Calculator");
    	system("COLOR 2");
    	char cChar;
    	double dfirstnumber;
    	double dsecondnumber;
    	char cDoagain;
    
    do
    {
    	system("CLS");
    	cout << "please enter the 1st number" 
    		<< endl;
    	cin >> dfirstnumber;
    	cout << "please enter the operation"
    		<< " (+,-,*,/)" << endl;
    	cin >> cChar;
    
    	cout << "please enter the 2nd number"
    		<< endl;
    
    	switch (cChar)
    	{
    	case '+':
    		cout << "the answer is: " << dfirstnumber << " + " <<
    			dsecondnumber << " = " << (dfirstnumber + dsecondnumber)
    			<< endl;
    		break;
    	case '-':
    		cout << "the answer is: " << dfirstnumber << " - " <<
    			dsecondnumber << " = " << (dfirstnumber - dsecondnumber)
    			<< endl;
    		break;
    	case '*':
    		cout << "the answer is: " << dfirstnumber << " * " <<
    			dsecondnumber << " = " << (dfirstnumber * dsecondnumber)
    			<< endl;
    		break;
    	case 'x':
    		cout << "the answer is: " << dfirstnumber << " x " <<
    			dsecondnumber << " = " << (dfirstnumber * dsecondnumber)
    			<< endl;
    		break;
    	case 'X':
    		cout << "the answer is: " << dfirstnumber << " X " <<
    			dsecondnumber << " = " << (dfirstnumber * dsecondnumber)
    			<< endl;
    		break;
    	case '/':
    		if(dsecondnumber == 0){
    			cout << "that is an invalid operation" << endl;
    		}else{
    		cout << "the answer is: " << dfirstnumber << " / " <<
    			dsecondnumber << " = " << (dfirstnumber / dsecondnumber)
    			<< endl;
    		}
    		break;
    	default:
    		cout << "that is an invalid operation" << endl;
    		break;
    	}
    	cout << "Would you like to start again? (y or n)" << endl;
    	cin >> cDoagain;
    }while (cDoagain == 'Y' || cDoagain == 'y');
    system("PAUSE");
    return 0;
    }

    i get this error

    1>Compiling...
    1>C++2.cpp
    1>c:usersownerdesktoppatrickc++c++2c++2c++2.cpp(1) : error C2001: newline in constant
    1>Build log was saved at "file://c:UsersOwnerDesktopPatrickC++C++2C++2DebugBuildLog.htm"
    1>C++2 - 1 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    i added the #include «stdafx.h» becuase of another error.
    also, im useing this tutorial from youtube
    http://www.youtube.com/watch?v=sIy3oOguh_0&fmt=18
    i did this before but in the program DevC++ it worked fine (and i didn’t have to add #include «stdafx.h)

    im now using Visual Studio 2008
    i have vista 64-bit (i did this last in XP 32-bit(with DevC++))
    Thanks

Answers

  • Quote>Error spawning ‘rc.exe’.

    rc.exe is the Microsoft Resource Compiler.

    It should have been installed with the Windows SDK. Check for it there.

    If you haven’t installed the SDK, you need to do so. (It should have been installed when you
    installed VC++ 2008. Earlier versions required explicit installation as a separate step.)

    — Wayne

    • Marked as answer by

      Tuesday, May 12, 2009 11:47 PM

    • Unmarked as answer by
      Patq911
      Wednesday, May 13, 2009 12:54 AM
    • Marked as answer by
      Wesley Yao
      Tuesday, May 19, 2009 5:28 AM

Понравилась статья? Поделить с друзьями:
  • Error c1083 cannot open include file no such file or directory
  • Error c000012f wine msi
  • Error c compiler cannot create executables centos
  • Error byte was not declared in this scope
  • Error by extcap pipe