Error m587 expected string expression

Fix “Expected Primary-Expression Before” in C++ or Arduino “Expected primary-expression before ‘some‘ token” is one of the most common errors that you

Fix “Expected Primary-Expression Before” in C++ or Arduino

“Expected primary-expression before ‘some‘ token” is one of the most common errors that you can experience in Arduino code. Arduino code is written in C++ with few additions here and there, so it is a C++ syntax error. There are multiple versions of this error, depends on what is it that you messed up. Some are easy to fix, some not so much.

Most of the times (but not always), the error occurs because you have missed something or put it at the wrong place. Be it a semicolon, a bracket or something else. It can be fixed by figuring out what is that you missed/misplaced and placing it at the right position. Let us walk through multiple versions of the error and how to fix them one by one.

We all like building things, don’t we? Arduino gives us the opportunity to do amazing things with electronics with simply a little bit of code. It is an open-source electronics platform. It is based on hardware and software which are easy to learn and use. If I were to explain in simple language what Arduino does – it takes an input from the user in different forms such as touch or light and turns it into an output such as running a motor. Actually, you can even post tweets on Twitter with Arduino.

Table of Contents

How to fix “Expected Primary-Expression Before” error?

I’ll walk you through multiple examples of where the error can occur and how to possibly fix it. The codes that I use as examples in this article are codes that people posted on forums asking for a solution, so all credits of the code go to them. Let’s begin.

Type 1: Expected primary-expression before ‘>’ token

This error occurs when when the opening curly brackets ‘<‘ are not properly followed by the closing curly bracket ‘>’. To fix this, what you have to do is: check if all of your opening and closing curly brackets match properly. Also, check if you are missing any curly brackets. There isn’t much to this, so I’ll move on to the other types.

Type 2: Expected primary expression before ‘)’ token

Example 1: All credits to this thread. Throughout all of my examples, I will highlight the line which is causing the issue with red.

Solution 1:

The error occurs in this code because the rainbow function is supposed to have a variable as its argument, however the argument given here is ‘uint8_t’ which is not a variable.

Here all you have to do is define uint8_t as a variable first and assign it a value. The code will work after that.

Type 3: Expected primary-expression before ‘enum’

Example 1: All credits to this thread.

Solution 1:

The “expected primary-expression before ‘enum’ ” error occurs here because the enum here has been defined inside a method, which is incorrect. The corrected code is:

Note: Another mistake has been fixed in this code i.e. the space in “Range Rover” variable. Variable names cannot contain spaces.

Type 4: Expected primary expression before ‘.’

Example 1: All credits go to this thread.

Solution 1: Here the error occurs because “square” is being used as an object, which it is not. Square is a type, and the corrected code is given below.

Type 5: Expected primary-expression before ‘word’

Example 1: All credits go to this thread.

Solution 1:

Here, they are incorrectly using string inside wordLengthFunction().

Fixing it is simple, simply replace

Type 6: Expected primary-expression before ‘else’

Example 1: All credit goes to this thread.

Solution 1:

This code is not correct because after the if statement is closed with ‘>’ in this code, there are two statements before the else statement starts. There must not be any statements between the closing curly bracket ‘>’ of if statement and the else statement. It can be fixed by simply removing the part that I have marked in red.

Conclusion

And that’s it, I hope you were able to fix the expected primary-expression before error. This article wasn’t easy to write – I’m in no way an expert in C++, but I do know it to a decent level. I couldn’t find any articles related to fixing this error on the internet so I thought I’d write one myself. Answers that I read in forums helped me immensely while researching for this article and I’m thankful to the amazing community of programmers that we have built! If you would like to ask me anything, suggest any changes to this article or simply would like to write for us/collaborate with us, visit our Contact page. Thank you for reading, I hope you have an amazing day.

Also, tell me which one of the 6 types were you experiencing in the comments below.

Источник

Fix “Expected Primary-Expression Before” in C++ or Arduino

“Expected primary-expression before ‘some‘ token” is one of the most common errors that you can experience in Arduino code. Arduino code is written in C++ with few additions here and there, so it is a C++ syntax error. There are multiple versions of this error, depends on what is it that you messed up. Some are easy to fix, some not so much.

Most of the times (but not always), the error occurs because you have missed something or put it at the wrong place. Be it a semicolon, a bracket or something else. It can be fixed by figuring out what is that you missed/misplaced and placing it at the right position. Let us walk through multiple versions of the error and how to fix them one by one.

We all like building things, don’t we? Arduino gives us the opportunity to do amazing things with electronics with simply a little bit of code. It is an open-source electronics platform. It is based on hardware and software which are easy to learn and use. If I were to explain in simple language what Arduino does – it takes an input from the user in different forms such as touch or light and turns it into an output such as running a motor. Actually, you can even post tweets on Twitter with Arduino.

Table of Contents

How to fix “Expected Primary-Expression Before” error?

I’ll walk you through multiple examples of where the error can occur and how to possibly fix it. The codes that I use as examples in this article are codes that people posted on forums asking for a solution, so all credits of the code go to them. Let’s begin.

Type 1: Expected primary-expression before ‘>’ token

This error occurs when when the opening curly brackets ‘<‘ are not properly followed by the closing curly bracket ‘>’. To fix this, what you have to do is: check if all of your opening and closing curly brackets match properly. Also, check if you are missing any curly brackets. There isn’t much to this, so I’ll move on to the other types.

Type 2: Expected primary expression before ‘)’ token

Example 1: All credits to this thread. Throughout all of my examples, I will highlight the line which is causing the issue with red.

Solution 1:

The error occurs in this code because the rainbow function is supposed to have a variable as its argument, however the argument given here is ‘uint8_t’ which is not a variable.

Here all you have to do is define uint8_t as a variable first and assign it a value. The code will work after that.

Type 3: Expected primary-expression before ‘enum’

Example 1: All credits to this thread.

Solution 1:

The “expected primary-expression before ‘enum’ ” error occurs here because the enum here has been defined inside a method, which is incorrect. The corrected code is:

Note: Another mistake has been fixed in this code i.e. the space in “Range Rover” variable. Variable names cannot contain spaces.

Type 4: Expected primary expression before ‘.’

Example 1: All credits go to this thread.

Solution 1: Here the error occurs because “square” is being used as an object, which it is not. Square is a type, and the corrected code is given below.

Type 5: Expected primary-expression before ‘word’

Example 1: All credits go to this thread.

Solution 1:

Here, they are incorrectly using string inside wordLengthFunction().

Fixing it is simple, simply replace

Type 6: Expected primary-expression before ‘else’

Example 1: All credit goes to this thread.

Solution 1:

This code is not correct because after the if statement is closed with ‘>’ in this code, there are two statements before the else statement starts. There must not be any statements between the closing curly bracket ‘>’ of if statement and the else statement. It can be fixed by simply removing the part that I have marked in red.

Conclusion

And that’s it, I hope you were able to fix the expected primary-expression before error. This article wasn’t easy to write – I’m in no way an expert in C++, but I do know it to a decent level. I couldn’t find any articles related to fixing this error on the internet so I thought I’d write one myself. Answers that I read in forums helped me immensely while researching for this article and I’m thankful to the amazing community of programmers that we have built! If you would like to ask me anything, suggest any changes to this article or simply would like to write for us/collaborate with us, visit our Contact page. Thank you for reading, I hope you have an amazing day.

Also, tell me which one of the 6 types were you experiencing in the comments below.

Источник

ошибка: ожидаемое первичное выражение до токена ‘=’ и многие другие

Либо я слепой, либо ошибки нет. Я думаю, что это был бы, вероятно, первый выбор. Пожалуйста, помогите мне найти иголку в стоге сена. Это часть моего списка ошибок:

и это часть моего кода:

У меня есть много подобных ошибок во всем коде, поэтому я думаю, что есть что-то вроде пропуска столбца или чего-то другого. Вы видите это? Я не.

Решение

Макрос не является переменной. Это не имеет значения. Это функция предварительной обработки.

Причина, по которой у вас везде появляются синтаксические ошибки, заключается в том, что ERR_OK и тому подобное были заменены = 0; скорее, чем 0 например.

Другие решения

Другие ответы верны, что проблема заключается в символических константах

Тем не менее, в C ++ есть лучший способ исправить это:

Или C и C ++ оба позволяют

Ваш #define s неверны, они должны выглядеть следующим образом, например:

То есть они не должны иметь = и не заканчивается точкой с запятой. #define это директива препроцессора. Они не подчиняются тем же правилам синтаксиса, что и остальная часть C ++. В частности, директива препроцессора завершается новой строкой, а не точкой с запятой.

Это на самом деле определяет ERR_PARAMS быть = 1; , Если потом заменить ERR_PARAMS с = 1; в своем коде вы увидите, почему всплывают некоторые ошибки. Например, рассмотрим эту строку:

Если вы замените ERR_PARAMS здесь вы получите:

Источник

Error m587 expected string expression

movie.h
lines 6-7: You don’t need to pass a pointer to movie as an argument. A function that is a member of a class implicity has access to the member variables of the class.

movie.cpp
Line 1,20: Ditto.

Line 13: Simply call enter_movie(). You don’t need to pass any arguments.

Lines 22-27: 1) You don’t need the m-> to call member functions of your class. 2) You don’t specify types in a function call. Types are only specified in a functin prototype. 3) Since you haven’t shown these functions, it’s not clear if these functions are prompting for input. If they are, you don’t need arguments at all.

main.cpp
line 5: 1) You have to pass an integer value, not a type. Again, you don’t specify types in a function call. 2) movie * is a type. You don’t need this argument since the instance of movie is specified by the Movie variable.

You are confusing two concepts:

1. Declaring and defining functions and members of classes.

2. Calling functions and members of classes ( whether you call a class member on an object or a static member on a class)

When you define a function, you have to add the type of the parameter:

Now I want to use the function I wrote:

What you do wrong in the main function:

Is calling the member function with types, instead of values or variables. Try this:

42 in my code is line 1 above.

I took out the pointers and the m->. I took out the parameters of all the function calls with two exceptions. Main line 5 and movie.cpp line 1 have a 0 in them and that’s it. Also in movie.cpp line 20 it’s now just void movie::enter_movie( movie ) . It wouldn’t let me take it out or it got mad at me. I don’t really know why I need the number in the two function calls to get rid of so many errors. I tried just declaring the function in the class without any parameters at all since I was asking for the number inside the function but it got mad at me for that too. Feels like c++ is just out to get me. I do things that seem logical to me but the compiler blows up overtime I try something. Anyways, any clues on that last error? 🙂

There are a few problems with the code you posted:
main.cpp
Line 5: There is no reason to dynamically allocate an instance of movie.
Line 6: As I pointed out before, there is no reason to pass a pointer to a movie instance assuming all the OP wants to do is update a single instance (Movie).
Line 7: You have a memory leak. The instance of movie that was dynamically allocated was never released.

@OP

It wouldn’t let me take it out or it got mad at me. I don’t really know why I need the number in the two function calls to get rid of so many errors.

In movie.cpp line 1, you’re passing choose as an argument. There is really no need for choose to be an argument since you prompt for it at line 7. However, if you remove choose as an argument, you must declare it locally within menu().

Ok here’s the whole thing, maybe that will clear any confusion of what I’ve attempted to do. Also there’s several blank functions that I just haven’t even gotten to yet because I either don’t know what I’m supposed to use it for or I’m waiting to get past these errors before I get into them. Figured I’d get past the current errors before I start making more. 🙂

output: refers to line 32 in this post.

I’m sorry if the things I’ve done in this code are just ridiculous. I’m amazingly terrible at coding despite spending all of my free time reading the 2 books I have and going to TA office hours. I took me a week just to figure out how to begin designing the thing and it’s been a week of me being stuck at this point. Seems like every thing I do make it worse. I am dying to understand this stuff so any thing you can say to help will be greatly appreciated. Thank you much. 🙂

movie.cpp line 32: get rid of the 0. This function should not have any arguments. 0 is not valid in an argument list.

main.cpp line 19: get rid of this line. There is no reason to dynamically allocate a move instance. It’s also causing a memory leak since you never delete it.

main.cpp line 20: get rid of the 0. You can’t pass a 0 to a function that doesn’t take any arguments.

movie.cpp line 30: If you’re going to pass an argument here, you need to name the argument.

Line 57, 69, 77, 85, 93, 106, 114: Again, if you’re going to pass and argument to these functions, you need to specify a name, not just a type. You can get away with not specifying a name in the declaration, but a name is required in the definition. However, I don’t see that you need any of these arguments.

movie.h line 17: Why is cast a pointer? In movie.cpp line 100, you’re trying to do a getline to a null pointer. That’s going to cause a trap or an exception.

I’m assuming your intention here is to allow multiple cast members. If that’s what you’re trying to do, you should use a vector:

Источник

End of Config.g

; Tools
M563 P0 D0 H1                               				; Define tool 0 and fan 0
G10 P0 X0 Y0 Z0                             				; Set tool 0 axis offsets
G10 P0 R0 S0                                				; Set initial tool 0 active and standby temperatures to 0C
T0															; select Tool 0


;Extrusion settings
M593 F39.1													;Resonance Frequency WIP

;Nonlinear extrusion
;M592 D0 A-0.057410915 B0.015877315							;Nonlinear extrusion WIP

M501														;load config-override


;Pressure Advance
;M572 D0 S0.22												;Rosa Silk PLA
;M572 D0 S0.15												;PLA
;M572 D0 S0.492												;PETG White 230
M572 D0 S0.08												;0.8 PLA


; Retraction
M207 S2 F3000 R0 T2200 Z0									;0.8 PLA
;M207 S2 F1400 R0 T1200 Z0									;0.8 PETG
;M207 S2 F3000 R0 T2500 Z0.0								;Silk PLA
;M207 S4 F3600 R0 T2400 Z0.2			       				;0.8 PLA
;M207 S2 F3600 R0 T2400 Z0.0		   						;ABS
;M207 S2 F3000 R0 T2500 Z0.0								;Blue Thumann
;M207 S4 F3000 R0 T2400 Z0.0								;PETG
;M207 S4 F1500 R0 T1200 Z0.0								;TPU TEST


T0

Sample G-code file:

; G-Code generated by Simplify3D(R) Version 4.1.2
; Sep 17, 2020 at 1:27:27 PM
; Settings Summary
;   processName,Process1
;   applyToModels,PredatorSpoolSupport_ExtendedGuide
;   profileName,Predator_Hatchbox_PETG (modified)
;   profileVersion,2020-09-14 19:46:39
;   baseProfile,M2-E3Dv6-0.4mm
;   printMaterial,PLA
;   printQuality,Medium
;   printExtruders,
;   extruderName,Left Extruder
;   extruderToolheadNumber,0
;   extruderDiameter,0.4
;   extruderAutoWidth,1
;   extruderWidth,0.48
;   extrusionMultiplier,1
;   extruderUseRetract,1
;   extruderRetractionDistance,1.6
;   extruderExtraRestartDistance,0
;   extruderRetractionZLift,0.6
;   extruderRetractionSpeed,3000
;   extruderUseCoasting,1
;   extruderCoastingDistance,0
;   extruderUseWipe,1
;   extruderWipeDistance,5
;   primaryExtruder,0
;   layerHeight,0.25
;   topSolidLayers,5
;   bottomSolidLayers,5
;   perimeterOutlines,3
;   printPerimetersInsideOut,1
;   startPointOption,2
;   startPointOriginX,0
;   startPointOriginY,0
;   sequentialIslands,0
;   spiralVaseMode,0
;   firstLayerHeightPercentage,95
;   firstLayerWidthPercentage,100
;   firstLayerUnderspeed,0.4
;   useRaft,0
;   raftExtruder,0
;   raftTopLayers,1
;   raftBaseLayers,1
;   raftOffset,5
;   raftSeparationDistance,0.4
;   raftTopInfill,80
;   aboveRaftSpeedMultiplier,0.3
;   useSkirt,1
;   skirtExtruder,0
;   skirtLayers,1
;   skirtOutlines,2
;   skirtOffset,5
;   usePrimePillar,0
;   primePillarExtruder,999
;   primePillarWidth,12
;   primePillarLocation,7
;   primePillarSpeedMultiplier,1
;   useOozeShield,0
;   oozeShieldExtruder,999
;   oozeShieldOffset,2
;   oozeShieldOutlines,1
;   oozeShieldSidewallShape,1
;   oozeShieldSidewallAngle,30
;   oozeShieldSpeedMultiplier,1
;   infillExtruder,0
;   internalInfillPattern,Triangular
;   externalInfillPattern,Rectilinear
;   infillPercentage,30
;   outlineOverlapPercentage,30
;   infillExtrusionWidthPercentage,103
;   minInfillLength,2
;   infillLayerInterval,1
;   internalInfillAngles,0,60,-60
;   overlapInternalInfillAngles,1
;   externalInfillAngles,45,135
;   generateSupport,1
;   supportExtruder,0
;   supportInfillPercentage,15
;   supportExtraInflation,1
;   supportBaseLayers,3
;   denseSupportExtruder,0
;   denseSupportLayers,3
;   denseSupportInfillPercentage,100
;   supportLayerInterval,1
;   supportHorizontalPartOffset,0.45
;   supportUpperSeparationLayers,4
;   supportLowerSeparationLayers,4
;   supportType,0
;   supportGridSpacing,1
;   maxOverhangAngle,60
;   supportAngles,0
;   temperatureName,Primary Extruder,Heated Bed
;   temperatureNumber,0,1
;   temperatureSetpointCount,2,2
;   temperatureSetpointLayers,1,2,1,2
;   temperatureSetpointTemperatures,240,240,80,80
;   temperatureStabilizeAtStartup,1,1
;   temperatureHeatedBed,0,1
;   fanLayers,1
;   fanSpeeds,0
;   blipFanToFullPower,1
;   adjustSpeedForCooling,1
;   minSpeedLayerTime,8
;   minCoolingSpeedSlowdown,30
;   increaseFanForCooling,0
;   minFanLayerTime,45
;   maxCoolingFanSpeed,100
;   increaseFanForBridging,0
;   bridgingFanSpeed,100
;   use5D,1
;   relativeEdistances,1
;   allowEaxisZeroing,1
;   independentExtruderAxes,0
;   includeM10123,0
;   stickySupport,1
;   applyToolheadOffsets,0
;   gcodeXoffset,0
;   gcodeYoffset,0
;   gcodeZoffset,0
;   overrideMachineDefinition,1
;   machineTypeOverride,1
;   strokeXoverride,260
;   strokeYoverride,260
;   strokeZoverride,410
;   originOffsetXoverride,130
;   originOffsetYoverride,130
;   originOffsetZoverride,0
;   homeXdirOverride,-1
;   homeYdirOverride,-1
;   homeZdirOverride,1
;   flipXoverride,1
;   flipYoverride,-1
;   flipZoverride,1
;   toolheadOffsets,0,0|0,0|0,0|0,0|0,0|0,0
;   overrideFirmwareConfiguration,1
;   firmwareTypeOverride,RepRap (Marlin/Repetier/Sprinter)
;   GPXconfigOverride,r2
;   baudRateOverride,250000
;   overridePrinterModels,0
;   printerModelsOverride
;   startingGcode,G28 ; home all axes,G29 S1 ; use previous mesh calibration,
;   layerChangeGcode,
;   retractionGcode,
;   toolChangeGcode,
;   endingGcode,G28 ; home all axes,M106 S0 ; turn off cooling fan,M104 S0 ; turn off extruder,M140 S0 ; turn off bed,M84 ; disable motors
;   exportFileFormat,gcode
;   celebration,0
;   celebrationSong,Star Wars
;   postProcessing,
;   defaultSpeed,3200
;   outlineUnderspeed,0.5
;   solidInfillUnderspeed,0.75
;   supportUnderspeed,0.75
;   rapidXYspeed,12000
;   rapidZspeed,1200
;   minBridgingArea,10
;   bridgingExtraInflation,1
;   bridgingExtrusionMultiplier,1.4
;   bridgingSpeedMultiplier,1.25
;   useFixedBridgingAngle,0
;   fixedBridgingAngle,0
;   applyBridgingToPerimeters,0
;   filamentDiameters,1.75|1.75|1.75|1.75|1.75|1.75
;   filamentPricesPerKg,24|26|26|26|26|26
;   filamentDensities,1.25|1.25|1.25|1.25|1.25|1.25
;   useMinPrintHeight,0
;   minPrintHeight,12
;   useMaxPrintHeight,0
;   maxPrintHeight,15
;   useDiaphragm,0
;   diaphragmLayerInterval,20
;   robustSlicing,1
;   mergeAllIntoSolid,0
;   onlyRetractWhenCrossingOutline,1
;   retractBetweenLayers,1
;   useRetractionMinTravel,0
;   retractionMinTravel,3
;   retractWhileWiping,1
;   onlyWipeOutlines,1
;   avoidCrossingOutline,0
;   maxMovementDetourFactor,3
;   toolChangeRetractionDistance,0
;   toolChangeExtraRestartDistance,0
;   toolChangeRetractionSpeed,360
;   externalThinWallType,1
;   internalThinWallType,2
;   thinWallAllowedOverlapPercentage,0
;   singleExtrusionMinLength,1
;   singleExtrusionMinPrintingWidthPercentage,50
;   singleExtrusionMaxPrintingWidthPercentage,200
;   singleExtrusionEndpointExtension,0.2
;   horizontalSizeCompensation,0
G90
M83
M106 S0
M140 S80
M190 S80
M104 S240 T0
M109 S240 T0
G28 ; home all axes
G29 S1 ; use previous mesh calibration
; process Process1
; layer 1, Z = 0.237
T0
G1 E-1.6000 F3000
; feature skirt
; tool H0.237 W0.480
G1 Z0.600 F1200
G1 X4.089 Y-25.940 F12000
G1 Z0.237 F1200
G1 E1.6000 F3000
G1 X4.911 Y-25.940 E0.0389 F1280
  1. Здравствуйте. Не компилируется скетч

    #define A  3;
    #define B  2;
    #define C 6;
    #define D 7;
    #define E 8;
    #define F 4;
    #define G 5;

    void setup()
    {
      pinMode (A, OUTPUT);
      pinMode (B, OUTPUT);
      pinMode (C, OUTPUT);
      pinMode (D, OUTPUT);
      pinMode (E, OUTPUT);
      pinMode (F, OUTPUT);
      pinMode (G, OUTPUT);

     
    }

    void loop()

    {
    int sensorValue = analogRead(A0);
    float voltage = sensorValue * (5.0 / 1024.0);

    if(voltage >3.9  && voltage <4.3  ) // LHH 4.05
        {
            digitalWrite(A, HIGH);
                    digitalWrite(B, HIGH);
                    digitalWrite(C, HIGH);
                    digitalWrite(D, HIGH);
                    digitalWrite(E, LOW);
                    digitalWrite(F, LOW);
                    digitalWrite(G, HIGH);
        }

    if(voltage > 3.1 && voltage <3.7 ) //HLH 3.4
        {
            digitalWrite(A, HIGH);
                    digitalWrite(B, LOW);
                    digitalWrite(C, HIGH);
                    digitalWrite(D, HIGH);
                    digitalWrite(E, LOW);
                    digitalWrite(F, HIGH);
                    digitalWrite(G, HIGH);
        }

    if(voltage > 1.95 && voltage < 2.15) //HLL 2.07
        {
            digitalWrite(A, LOW);
                    digitalWrite(B, HIGH);
                    digitalWrite(C, HIGH);
                    digitalWrite(D, LOW);
                    digitalWrite(E, LOW);
                    digitalWrite(F, HIGH);
                    digitalWrite(G, HIGH);
        }

    if(voltage > 2.15 && voltage < 2.6) //LHL 2.3
        {
            digitalWrite(A, HIGH);
                    digitalWrite(B, HIGH);
                    digitalWrite(C, LOW);
                    digitalWrite(D, HIGH);
                    digitalWrite(E, HIGH);
                    digitalWrite(F, LOW);
                    digitalWrite(G, HIGH);
        }

    if(voltage > 2.65 && voltage < 3.25) //LLH 2.93
        {
            digitalWrite(A, LOW);
                    digitalWrite(B, HIGH);
                    digitalWrite(C, HIGH);
                    digitalWrite(D, LOW);
                    digitalWrite(E, LOW);
                    digitalWrite(F, LOW);
                    digitalWrite(G, LOW);
        }

    if(voltage > 1.7 && voltage < 2.15) //LLL 1.89
        {
            digitalWrite(A, LOW);
                    digitalWrite(B, HIGH);
                    digitalWrite(C, HIGH);
                    digitalWrite(D, LOW);
                    digitalWrite(E, HIGH);
                    digitalWrite(F, HIGH);
                    digitalWrite(G, HIGH);
        }

    if(voltage > 2.35 && voltage < 2.75) //HHL 2.58
        {
            digitalWrite(A, HIGH);
                    digitalWrite(B, HIGH);
                    digitalWrite(C, HIGH);
                    digitalWrite(D, LOW);
                    digitalWrite(E, HIGH);
                    digitalWrite(F, HIGH);
                    digitalWrite(G, HIGH);
        }

    }

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

    In function ‘void setup()’:
    11: error: expected `)’ before ‘;’ token
    11: error: expected primary-expression before ‘,’ token
    11: error: expected `;’ before ‘)’ token
    12: error: expected `)’ before ‘;’ token
    12: error: expected primary-expression before ‘,’ token
    12: error: expected `;’ before ‘)’ token
    13: error: expected `)’ before ‘;’ token
    13: error: expected primary-expression before ‘,’ token
    13: error: expected `;’ before ‘)’ token
    14: error: expected `)’ before ‘;’ token
    14: error: expected primary-expression before ‘,’ token
    14: error: expected `;’ before ‘)’ token
    15: error: expected `)’ before ‘;’ token
    15: error: expected primary-expression before ‘,’ token
    15: error: expected `;’ before ‘)’ token
    16: error: expected `)’ before ‘;’ token
    16: error: expected primary-expression before ‘,’ token
    16: error: expected `;’ before ‘)’ token
    17: error: expected `)’ before ‘;’ token
    17: error: expected primary-expression before ‘,’ token
    17: error: expected `;’ before ‘)’ token
    In function ‘void loop()’:
    29: error: expected `)’ before ‘;’ token
    29: error: expected primary-expression before ‘,’ token
    29: error: expected `;’ before ‘)’ token
    30: error: expected `)’ before ‘;’ token
    30: error: expected primary-expression before ‘,’ token
    30: error: expected `;’ before ‘)’ token
    31: error: expected `)’ before ‘;’ token
    31: error: expected primary-expression before ‘,’ token
    31: error: expected `;’ before ‘)’ token
    32: error: expected `)’ before ‘;’ token
    32: error: expected primary-expression before ‘,’ token
    32: error: expected `;’ before ‘)’ token
    33: error: expected `)’ before ‘;’ token
    33: error: expected primary-expression before ‘,’ token
    33: error: expected `;’ before ‘)’ token
    34: error: expected `)’ before ‘;’ token
    34: error: expected primary-expression before ‘,’ token
    34: error: expected `;’ before ‘)’ token
    35: error: expected `)’ before ‘;’ token
    35: error: expected primary-expression before ‘,’ token
    35: error: expected `;’ before ‘)’ token
    40: error: expected `)’ before ‘;’ token
    40: error: expected primary-expression before ‘,’ token
    40: error: expected `;’ before ‘)’ token
    41: error: expected `)’ before ‘;’ token
    41: error: expected primary-expression before ‘,’ token
    41: error: expected `;’ before ‘)’ token
    42: error: expected `)’ before ‘;’ token
    42: error: expected primary-expression before ‘,’ token
    42: error: expected `;’ before ‘)’ token
    43: error: expected `)’ before ‘;’ token
    43: error: expected primary-expression before ‘,’ token
    43: error: expected `;’ before ‘)’ token
    44: error: expected `)’ before ‘;’ token
    44: error: expected primary-expression before ‘,’ token
    44: error: expected `;’ before ‘)’ token
    45: error: expected `)’ before ‘;’ token
    45: error: expected primary-expression before ‘,’ token
    45: error: expected `;’ before ‘)’ token
    46: error: expected `)’ before ‘;’ token
    46: error: expected primary-expression before ‘,’ token
    46: error: expected `;’ before ‘)’ token
    51: error: expected `)’ before ‘;’ token
    51: error: expected primary-expression before ‘,’ token
    51: error: expected `;’ before ‘)’ token
    52: error: expected `)’ before ‘;’ token
    52: error: expected primary-expression before ‘,’ token
    52: error: expected `;’ before ‘)’ token
    53: error: expected `)’ before ‘;’ token
    53: error: expected primary-expression before ‘,’ token
    53: error: expected `;’ before ‘)’ token
    54: error: expected `)’ before ‘;’ token
    54: error: expected primary-expression before ‘,’ token
    54: error: expected `;’ before ‘)’ token
    55: error: expected `)’ before ‘;’ token
    55: error: expected primary-expression before ‘,’ token
    55: error: expected `;’ before ‘)’ token
    56: error: expected `)’ before ‘;’ token
    56: error: expected primary-expression before ‘,’ token
    56: error: expected `;’ before ‘)’ token
    57: error: expected `)’ before ‘;’ token
    57: error: expected primary-expression before ‘,’ token
    … и так далее

    Категорически не понимаю, в чем проблема. Ткните носом, пожалуйста.

  2. Тыкаю. Прямо в первой строке кода. И во второй. И еще в следующих.

  3. В дефайнах уберите точки с запятой.

  4. Спасибо, запятые удалил. Теперь почему-то не видит F
    error: ‘F’ was not declared in this scope
    Хотя

  5. Поменяйте F на FF или еще на что-нибудь другое. И все получится.

  6. В дефайнах не рекомендуется использовать однобуквенные обозначения, чтобы не было конфликтов с системными переменными.

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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>  
 
#define MAX_SIZE 30
 
typedef struct User_t 
{ 
    char  *login; 
    char  *password; 
    char  *name;
    char  *sex; 
    int    age;
    int    id;  
    float  height; 
    float  weight;
}User;
 
 
/*+*/void clean_memory(User** users, unsigned size)
{
int i;
    for(i=0;i<size;i++)
    {
        free((*users)[size].login);
        free((*users)[size].password);
        free((*users)[size].name);
        free((*users)[size].sex);
    }
free(*users);
*users = NULL;
} 
 
/*+*/void output_f(User** users) 
{ 
int value,n,i;
    printf ("1 - output single data");
    printf ("2 - output all data");
    printf ("select an action : n");
        scanf ("%d",&n);
    switch(n)
    {
        case 1:
            printf ("Input user's id");
                scanf ("%d",value);
            printf ("{id: %d, login: "%s", password: "%s"}n{ name: "%s", sex: "%s", age: %d}n { height:%f, weight:%f}n",
                    (*users)[value].id,(*users)[value].login,(*users)[value].password,(*users)[value].name,(*users)[value].sex,
                (*users)[value].age,(*users)[value].height,(*users)[value].weight);
        break;
        case 2:
            for(i=0;i<value;i++)
                printf("{id: %d, login: "%s", password: "%s"}n{ name: "%s", sex: "%s", age: %d}n { height:%f, weight:%f}n", 
                        (*users)[value].id, (*users)[value].login, (*users)[value].password,(*users)[value].name,(*users)[value].sex,
                        (*users)[value].age,(*users)[value].height,(*users)[value].weight);
        break;
        default :
        break;
    }
}
 
/*+*/void include_f(User** users, unsigned size)  
{
char buffer[128];
bool sex;       
        printf("Input user's loginn");
            scanf("%127s", buffer);
                (users*)[size].login = (char*) malloc(strlen(buffer) + 1); 
                strcpy((users*)[size].login, buffer); 
        printf("Input user's passwordn"); 
            scanf("%127s", buffer);
                (users*)[size].password = (char*) malloc(strlen(buffer) + 1); 
                strcpy((users*)[size].password, buffer);  
        printf("Input user's namen");
            scanf("%127s", buffer);
                (users*)[size].name = (char*) malloc(strlen(buffer) + 1);
                strcpy((users*)[size].name, buffer); 
        printf("Input user's sex(0-female or 1-male)n"); 
            scanf("%d",sex); 
switch(sex) 
{ 
    case 0: 
        (users*)[size].sex=(char*) malloc(strlen("female")+1);
        strcpy((users*)[size].sex, buffer); 
        break; 
    case 1: 
        (users*)[size].sex=(char*) malloc(strlen("male")+1);
        strcpy((users*)[size].sex, buffer); 
        break;
    default:
        break; 
}
        printf("Input user's agen"); 
            scanf("%d",(users*)[size].age); 
        printf("Input user's heightn"); 
            scanf("%f",(users*)[size].height); 
        printf("Input user's weightn"); 
            scanf("%f",(users*)[size].weight); 
}
 
/*+*/void delete_f(User** users) 
{
int value; 
    printf("Input user's id"); 
        scanf("%d",value); 
    free((*users)[value].login);
    free((*users)[value].password);
    free((*users)[value].name);
    free((*users)[value].sex);
users[value] = NULL;
}
 
void search_f(User** users) 
{
 
}
 
void sort_f(User** users) 
{
int value;
    printf("set the sort task:");
    printf("1 - age n");
    printf("2 - height n");
    printf("3 - weight n");
    printf("4 - sex (male->female) n");
    printf("5 - ABC(A->Z) n");
        scanf("%d",value);
    switch(value)
    {
        case 1:
            break;
        case 2:
            break;
        case 3:
            break;
        case 4:
            break;
        case 5:
            break;
        default :
            printf("input right valuen");
            break;  
    }
}
 
/*+*/void edit_f(User** users) 
{
int value;
bool sex;
char buffer[128]; 
    printf ("Input user's id"); 
        scanf ("%d",value); 
        printf ("Input user's loginn");
            scanf("%127s", buffer);
            (users*)[value].login = (char*) malloc(strlen(buffer) + 1); 
            strcpy((users*)[value].login, buffer); 
        printf("Input user's passwordn"); 
            scanf("%127s", buffer);
            (users*)[value].password = (char*) malloc(strlen(buffer) + 1);  
            strcpy((users*)[value].password, buffer); 
        printf("Input user's namen");
            scanf("%127s", buffer);
            (users*)[value].name = (char*) malloc(strlen(buffer) + 1);
            strcpy((users*)[value].name, buffer); 
        printf("Input user's sex(0-female or 1-male)n"); 
            scanf("%d",sex); 
switch(sex) 
{ 
    case 0:  
        (users*)[value].sex=(char*) malloc(strlen("female")+1);
        strcpy((users*)[value].sex, "female");  
        break; 
    case 1: 
        (users*)[value].sex=(char*) malloc(strlen("male")+1);
        strcpy((users*)[value].sex, "male"); 
        break;
    default:
        break; 
}
        printf("Input user's agen"); 
            scanf("%d",(users*)[value].age); 
        printf("Input user's heightn"); 
            scanf("%f",(users*)[value].height); 
        printf("Input user's weightn"); 
            scanf("%f",(users*)[value].weight); 
}
 
/*+*/void input_f(User** users,unsigned size) 
{ 
unsigned i;
char buffer[128]; 
bool sex;    
    for(i=0;i<size;i++) 
    { 
        (*users)->id=i; 
        printf("Input user's #%dnlogin",i);
            scanf("%127s", buffer);
                (*users)[i].login = (char*) malloc(strlen(buffer) + 1);
                strcpy((*users)[i].login, buffer); 
        printf("Input user's passwordn"); 
            scanf("%127s", buffer); 
                (*users)[i].password = (char*) malloc(strlen(buffer) + 1);  
                strcpy((*users)[i].password, buffer);
        printf("Input user's nnamen");
            scanf("%127s", buffer);
                (*users)[i].name = (char*) malloc(strlen(buffer) + 1);
                strcpy((*users)[i].name, buffer);
        printf("Input user's sex(0-female or 1-male)n"); 
            scanf("%d",sex); 
switch(sex) 
{ 
    case 0: 
        (*users)[i].sex=(char*) malloc(strlen("female")+1);
        strcpy((*users)[i].sex, "female");
        break; 
    case 1: 
        (*users)[i].sex=(char*) malloc(strlen("male")+1);
        strcpy((*users)[i].sex, "male");
        break;
    default:
        break; 
}
        printf("Input user's agen"); 
            scanf("%d",(*users)[i].age); 
        printf("Input user's heightn"); 
            scanf("%f",(*users)[i].height); 
        printf("Input user's weightn"); 
            scanf("%f",(*users)[i].weight); 
    }  
}
 
int main () 
{
User *users = NULL;
unsigned size,value; 
 
bool program=true; 
    printf("Input number of usersn"); 
        scanf("%d",&size);
size = size <= MAX_SIZE? size: MAX_SIZE;
users = (User*) malloc((size+3) * sizeof(User));     
    /*+*/printf("1 - inputn"); 
    /*+*/printf("2 - outputn"); 
    /*+*/printf("3 - include (from the end )n"); 
    /*+*/printf("4 - deleten"); 
    printf("5 - searchn"); 
    printf("6 - sortn");
    /*+*/printf("7 - editn"); 
    /*+*/printf("8 - exitn");  
    while (program) 
    {
        printf("select an action : n");
            scanf("%d", value);
        switch(value) 
        { 
            case 1: 
                input_f(&users,size);  
                break; 
            case 2: 
                output_f(&users);  
                break; 
            case 3:  
                include_f(&users,size);
                size++;  
                break; 
            case 4: 
                delete_f(&users); 
                break; 
            case 5: 
                search_f(&users); 
                break; 
            case 6: 
                sort_f(&users); 
                break;
            case 7: 
                edit_f(&users); 
                break;   
            case 8: 
                program=false; 
                break;
            default:
                printf("input right valuen");
                break;
 
        }   
    }
clean_memory(&users,size);
return 0; 
}

Не обломался и вчитался :)

Учитесь читать то, что вам пишет компилятор. Первая же строка:

main.cpp(15) : error C2143: syntax error : missing ';' before '}'
//...

говорит о том, что на строке 15 не хватает ; перед }. Посмотрим:

//...
    struct gms_t* next    //указатель на следующий элемент
}gms;
//...

Действительно, не хватает. Исправляем (после next поставьте ;), снова компилируем. Следующая ошибка:

main.cpp(41) : error C3861: 'ad': identifier not found

Компилятор не знает, что такое ad. Смотрю на код. Оказывается, это функция, но она определена ниже, чем используется. Тут есть 2 варианта:

  1. переместить определение функции ad() до функции, откуда ad() вызывается (это main()).
  2. Оставить все определения функций на своих местах. Добавить объявление функции ad() до вызова.

Пойдем по второму пути. Заодно объявим другие функции, которые будут вызваны выше, чем определены:

// объявления функций
pelem ad();
void ed(pelem p);
void del(char obj_data[]);
void sort();
void rd(pelem p);

int main()
{
//...

Следующая ошибка:

main.cpp(49) : error C2275: 'pelem' : illegal use of this type as an expression

Посмотрите на 49-ю строку:

  case 2 : ed(pelem p); break;

Зачем тут тип pelem? Типичная ошибка программирования методом copy-paste. Исправляем это и такую же ошибку на 50й и 52й строках:

  case 1 : ad();break;
  case 2 : ed(p); break;
  case 3 : del(obj_data); break;
  case 4 : sort(); break;
  case 5 : rd(p); break;

Дальше.

main.cpp(49) : error C2065: 'p' : undeclared identifier

Наверное, название переменной p тоже осталось после copy-paste. Судя по коду функции ed(pelem p), Вы планируете изменить элемент списка. Но какой? Сперва пытаетесь вызывать функцию ad(), но делаете это неправильно.

void ed(pelem p) //редактирование элемента
{
pelem ad();

Тип возвращаемого значения тут уже не нужен. А то, что функция возвращает, вы не используете.

Дальше читаю код:

pelem ad() //добавление элемента
{
   pelem neo = (pelem) malloc(sizeof(gms));

И тут пламенный порыв помочь новичку угасает навсегда. Срочно бегите к семинаристу, посыпайте голову пеплом, и признайтесь ему, что не понимаете синтаксиса языка C++, не знаете, как работает malloc. Попросите дополнительно позаниматься с Вами!!!

Либо я слепой, либо ошибки нет. Я думаю, что это был бы, вероятно, первый выбор. Пожалуйста, помогите мне найти иголку в стоге сена. Это часть моего списка ошибок:

server.cpp: In function ‘int main(int, char**)’:
server.cpp:64:16: error: expected primary-expression before ‘=’ token
server.cpp:71:14: error: expected primary-expression before ‘=’ token
server.cpp:71:24: error: expected primary-expression before ‘)’ token
server.cpp:71:24: error: expected ‘;’ before ‘)’ token
server.cpp:72:12: error: expected primary-expression before ‘=’ token
server.cpp:80:10: error: expected primary-expression before ‘=’ token
make: *** [server] Error 1

и это часть моего кода:

#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <netdb.h>
#include <iostream>
#include <regex.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <string>
#include <stdlib.h>
#include <locale.h>
#include <cstring>
#include <signal.h>
#include <dirent.h>

using namespace std;

/* global variables */
// error codes
#define ERR_OK = 0;
#define ERR_PARAMS = 1;
#define ERR_SOCKET = 2;
#define ERR_BIND = 3;
#define ERR_OTHER = 99;

// others
#define LISTEN_BACKLOG 50

/* function prototypes */
void printErr(int EC);
int second(int port);

int main(int argc, char **argv)
{
int pflag = 0;
string pvalue;
int port;
int c;

opterr = 0;
while((c = getopt (argc, argv, "p:")) != -1) {
switch(c) {
case 'p':
pflag = 1;
pvalue.assign(optarg);
break;
case '?':
if(optopt == 'c')
fprintf(stderr, "Option -%c requires an argument.n", optopt);
else if(isprint (optopt))
fprintf(stderr, "Unknown option `-%c'.n", optopt);
else
fprintf(stderr, "Unknown option character `\x%x'.n", optopt);
return ERR_PARAMS;
default:
abort();
}
}

if(pflag == 0) {
printErr(ERR_PARAMS);
return ERR_PARAMS;
}
printf ("pvalue = %sn", pvalue.c_str());

port = atoi(pvalue.c_str());

second(port);

return ERR_OK;
}

У меня есть много подобных ошибок во всем коде, поэтому я думаю, что есть что-то вроде пропуска столбца или чего-то другого. Вы видите это? Я не.

-1

Решение

#define ERR_OK = 0;
#define ERR_PARAMS = 1;
#define ERR_SOCKET = 2;
#define ERR_BIND = 3;
#define ERR_OTHER = 99;

должно быть

#define ERR_OK 0
#define ERR_PARAMS 1
#define ERR_SOCKET 2
#define ERR_BIND 3
#define ERR_OTHER 99

Макрос не является переменной. Это не имеет значения. Это функция предварительной обработки.

Причина, по которой у вас везде появляются синтаксические ошибки, заключается в том, что ERR_OK и тому подобное были заменены = 0; скорее, чем 0 например.

4

Другие решения

Другие ответы верны, что проблема заключается в символических константах

#define ERR_OK = 0;
#define ERR_PARAMS = 1;
#define ERR_SOCKET = 2;
#define ERR_BIND = 3;
#define ERR_OTHER = 99;

Тем не менее, в C ++ есть лучший способ исправить это:

const int ERR_OK = 0;
const int ERR_PARAMS = 1;
const int ERR_SOCKET = 2;
const int ERR_BIND = 3;
const int ERR_OTHER = 99;

Или C и C ++ оба позволяют

enum ERROR_CODES {
ERR_OK,
ERR_PARAMS,
ERR_SOCKET,
ERR_BIND,
ERR_OTHER = 99
};

5

Ваш #defines неверны, они должны выглядеть следующим образом, например:

#define ERR_PARAMS 1

То есть они не должны иметь = и не заканчивается точкой с запятой. #define это директива препроцессора. Они не подчиняются тем же правилам синтаксиса, что и остальная часть C ++. В частности, директива препроцессора завершается новой строкой, а не точкой с запятой.

#define ERR_PARAMS = 1;

Это на самом деле определяет ERR_PARAMS быть = 1;, Если потом заменить ERR_PARAMS с = 1; в своем коде вы увидите, почему всплывают некоторые ошибки. Например, рассмотрим эту строку:

printErr(ERR_PARAMS);

Если вы замените ERR_PARAMS здесь вы получите:

printErr(= 1;);

Ну, это, конечно, не правильно!

4

#define ERR_OK = 0;
#define ERR_PARAMS = 1;
#define ERR_SOCKET = 2;
#define ERR_BIND = 3;
#define ERR_OTHER = 99;

должно быть

#define ERR_OK 0
#define ERR_PARAMS 1
#define ERR_SOCKET 2
#define ERR_BIND 3
#define ERR_OTHER 99

1

We have been working on this «disaster bot» code for days and hours. AFter all of our hard work, Arduino gives us this error code: expected primary-expression before void. Please please please assist we are so desperate to get this to work. Here is our code below. Please.

// HEARTBEAT SENSOR (displays heart rate on LCD screen)
int sensorPin = A0; // This is the analog sensor pin the backwards S pin is connected to
                           // you can use any of the analog pins, but would need to change this to match
double alpha = 0.75; // This code uses a rather cool way of averaging the values, using 75% of the 
                               // average of the previous values and 25% of the current value.
int period = 20; // This is how long the code delays in milliseconds between readings (20 mSec)
int in = 8;
int Reset=6;
int start=7;
int count=0,i=0,k=0,rate=0;

// LCD SCREEN
#include<LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

// BIG SOUND SENSOR
int soundDetectedPin = 10;
int soundDetectedVal = HIGH;
boolean bAlarm = false;

unsigned long lastSoundDetectTime;

int soundAlarmTime = 500;

// PUSH BUTTON AND BUZZER
int buzzer = 3;
int ledPin = 13;
int inPin = 7;
int val = 0;

#define sing

#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
#define NOTE_D1  37
#define NOTE_DS1 39
#define NOTE_E1  41
#define NOTE_F1  44
#define NOTE_FS1 46
#define NOTE_G1  49
#define NOTE_GS1 52
#define NOTE_A1  55
#define NOTE_AS1 58
#define NOTE_B1  62
#define NOTE_C2  65
#define NOTE_CS2 69
#define NOTE_D2  73
#define NOTE_DS2 78
#define NOTE_E2  82
#define NOTE_F2  87
#define NOTE_FS2 93
#define NOTE_G2  98
#define NOTE_GS2 104
#define NOTE_A2  110
#define NOTE_AS2 117
#define NOTE_B2  123
#define NOTE_C3  131
#define NOTE_CS3 139
#define NOTE_D3  147
#define NOTE_DS3 156
#define NOTE_E3  165
#define NOTE_F3  175
#define NOTE_FS3 185
#define NOTE_G3  196
#define NOTE_GS3 208
#define NOTE_A3  220
#define NOTE_AS3 233
#define NOTE_B3  247
#define NOTE_C4  262
#define NOTE_CS4 277
#define NOTE_D4  294
#define NOTE_DS4 311
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_GS4 415
#define NOTE_A4  440
#define NOTE_AS4 466
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_CS5 554
#define NOTE_D5  587
#define NOTE_DS5 622
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_FS5 740
#define NOTE_G5  784
#define NOTE_GS5 831
#define NOTE_A5  880
#define NOTE_AS5 932
#define NOTE_B5  988
#define NOTE_C6  1047
#define NOTE_CS6 1109
#define NOTE_D6  1175
#define NOTE_DS6 1245
#define NOTE_E6  1319
#define NOTE_F6  1397
#define NOTE_FS6 1480
#define NOTE_G6  1568
#define NOTE_GS6 1661
#define NOTE_A6  1760
#define NOTE_AS6 1865
#define NOTE_B6  1976
#define NOTE_C7  2093
#define NOTE_CS7 2217
#define NOTE_D7  2349
#define NOTE_DS7 2489
#define NOTE_E7  2637
#define NOTE_F7  2794
#define NOTE_FS7 2960
#define NOTE_G7  3136
#define NOTE_GS7 3322
#define NOTE_A7  3520
#define NOTE_AS7 3729
#define NOTE_B7  3951
#define NOTE_C8  4186
#define NOTE_CS8 4435
#define NOTE_D8  4699
#define NOTE_DS8 4978

#define melodyPin 3
//Hotline Bling Melody
int hotlineb_melody[] = {
  0, NOTE_D5, NOTE_D5, NOTE_D5,
  NOTE_F5, NOTE_E5, NOTE_D5, NOTE_C5,
  NOTE_E5, NOTE_C5, 0,  NOTE_F5,
  NOTE_E5, NOTE_D5, NOTE_C5, NOTE_E5,

  NOTE_C5, NOTE_A4, NOTE_F5, NOTE_E5,
  NOTE_D5, NOTE_C5, NOTE_E5, NOTE_C5,
  0, NOTE_F5, NOTE_E5, NOTE_D5,
  NOTE_C5, NOTE_E5, NOTE_C5, NOTE_A4,

  NOTE_F5, NOTE_C6, NOTE_C6,
  NOTE_C6, NOTE_A5, NOTE_C6, NOTE_C6,
  NOTE_D6, 0, NOTE_F5, NOTE_A5,
  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,

  NOTE_A5, 0, NOTE_C6, NOTE_C6,
  NOTE_C6, NOTE_A5, NOTE_C6, NOTE_C6,
  NOTE_D6, 0, NOTE_F5, NOTE_A5,
  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,

  NOTE_A5, NOTE_C6, NOTE_A5, NOTE_C6,
  NOTE_A5, NOTE_C6, NOTE_A5, NOTE_C6,
  NOTE_A5, NOTE_D6, NOTE_A5, NOTE_A5,
  NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5,

  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,
  NOTE_A5, NOTE_A5, NOTE_A5, NOTE_A5,
  NOTE_AS5, NOTE_A5, NOTE_G5, NOTE_F5,
  NOTE_G5, NOTE_G5, NOTE_A5, NOTE_A5,

  NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5,
  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,
  NOTE_F5, NOTE_C6, NOTE_A5, NOTE_C6,
  NOTE_A5, NOTE_C6, NOTE_A5, NOTE_C6,

  NOTE_A5, NOTE_D6, NOTE_A5, NOTE_A5,
  NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5,
  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,
  NOTE_A5, NOTE_A5, NOTE_A5, NOTE_A5,

  NOTE_AS5, NOTE_A5, NOTE_G5, NOTE_F5,
  NOTE_G5, NOTE_G5, NOTE_A5, NOTE_A5,
  NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5,
  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_A5, NOTE_G5
};

//HotlineBLING tempo
  int hotlineb_tempo[] = {
  12, 12, 12, 12,
  12, 12, 12, 12,
  6, 2, 3, 12,
  12, 12, 12, 3,

  3, 3, 12, 12,
  12, 12, 6, 2,
  3, 12, 12, 12,
  12, 3, 3, 4,

  12, 12, 12,
  12, 12, 12, 12,
  2, 3, 12, 12,
  12, 12, 12, 12,

  2, 3, 12, 12,
  12, 12, 12, 12,
  3, 3, 12, 12,
  12, 12, 12, 12,

  2, 12, 12, 12,
  12, 12, 12, 12,
  12, 1.5, 12, 12,
  12, 12, 12, 12,

  12, 12, 6, 2,
  12, 12, 12, 12,
  12, 12, 12, 12,
  6, 2, 12, 12,

  12, 12, 12, 12,
  12, 12, 6, 2.4,
  12, 12, 12, 12,
  12, 12, 12, 12,

  12, 1.5, 12, 12,
  12, 12, 12, 12,
  12, 12, 6, 2,
  12, 12, 12, 12,

  12, 12, 12, 12,
  6, 2, 12, 12,
  12, 12, 12, 12,
  12, 12, 8, 24, 2
};

void setup() {


{
  //lcd.createChar(1, heart);
  lcd.begin(16,2);

  lcd.print("Heart Beat");
  lcd.write(1);
  lcd.setCursor(0,1);
  lcd.print("Monitering");
  pinMode(in, INPUT);
  pinMode(Reset, INPUT);
  pinMode(start, INPUT);
  digitalWrite(Reset, HIGH);
  digitalWrite(start, HIGH);
  delay(1000);

  lcd.begin(16,2);
  lcd.print("need to talk?");
  delay(1000);

  lcd.begin(16,2);
  lcd.print("not yet satisfied with care?");
  delay(1000);
}
// This code runs on startup, it sets ledPin to output so it can blink the LED that is built into the
// Arduino (but then never does), and sets the serial port up for fast 115,200 baud communication
// of the values (make sure you change your serial monitor to match).


  Serial.begin (115200); // the baud rate of the serial data
  {
    Serial.begin(115200);
    pinMode (soundDetectedPin, INPUT);
  }
  //PUSH BUTTON AND BUZZER
  {
    pinMode(buzzer, OUTPUT);
    pinMode(13, OUTPUT);
    pinMode(inPin, INPUT);
    }
}

void loop() {
  // HEARTBEAT SENSOR
    static double oldValue = 0; // used for averaging.
    static double oldChange = 0; // not currently used
    int rawValue = analogRead (sensorPin); // This reads in the value from the analog pin.
                                                              // this is a 10 bit number, and will be between 0 and 1023
                                                              // If this value doesn't change, you've connected up
                                                              // something wrong


  unsigned long time2,time1;
  unsigned long time;

    double value = alpha * oldValue + (1 - alpha) * rawValue; // Calculate an average using 75% of the
                                                                                         // previous value and 25% of the new 

    Serial.print (rawValue); // Send out serially the value read in
    Serial.print (",");          // Send a comma
    Serial.println (value);   // Send out the average value and a new line
    oldValue = value;        // Save the average for next iteration
    delay (period);            // Wait 20 mSec

  if((digitalRead(start)))
  {
    k=0;
    lcd.clear();
    lcd.print("Please wait.......");
    while(k<5)
    {
     if(digitalRead(in))
     {
      if(k==0)
      time1=millis();
      k++;
      while(digitalRead(in));
     }
    }
      time2=millis();
      rate=time2-time1;
      rate=rate/5;
      rate=60000/rate;
      lcd.clear();
      lcd.print("Heart Beat Rate:");
      lcd.setCursor(0,1);
      lcd.print(rate);
      lcd.print(" ");
      lcd.write(1);      
      k=0;
      rate=0;
    }

  if(!digitalRead(Reset))
  {

      rate=0;
      lcd.clear();
      lcd.print("Heart Beat Rate:");
      lcd.setCursor(0,1);
      lcd.write(1);
      lcd.print(rate);
      k=0;
  }
  // LCD SCREEN (helpful hotlines message)
  {
    lcd.setCursor(0,1);
    lcd.clear();
    lcd.begin(16,2);
    lcd.print("1-800-273-8255");
    delay(1000);
    lcd.clear();
    lcd.begin(16,2);
    lcd.print("1-877-726-4727");
    delay(1000);
  }
  // BIG SOUND SENSOR
  {
    soundDetectedVal = digitalRead(soundDetectedPin);

    if (soundDetectedVal == LOW)
    {
      lastSoundDetectTime = millis();
      if (!bAlarm){
        Serial.println("you're doing great :)");
        bAlarm = true;
      }
    }
    else
    {
      if( (millis()-lastSoundDetectTime) > soundAlarmTime && bAlarm) {
        Serial.println("keep breathing");
        bAlarm = false;
      }
    }
  }
  // LCD SCREEN (are feeling better/listen to these sick tunes buddy message)
  {
    lcd.setCursor(0,1);
    lcd.clear();
    lcd.begin(16,2);
    lcd.print("if still need comfort");
    delay(500);
    lcd.clear();
    lcd.begin(16,2);
    lcd.print("hold button");
    delay(1000);
    }
    //PUSH BUTTON AND BUZZER
    {
      val = digitalRead(inPin);
      if (val == HIGH) {
        digitalWrite(buzzer, LOW);
      } else {
        digitalWrite(buzzer, HIGH);
      }
      }
// BUZZER
{{
  sing(1);
  sing(1);
  sing(2);
  }
  int song = 0;
   void sing(int s) {
    song = s;
    if (song == 1) {
      Serial.println("recognize this?");
      int size = sizeof(hotlineb_melody) / sizeof(int);
      for (int thisNote = 0; thisNote < size; thisNote++) {
        int noteDuration = 1000 / hotlineb_tempo[thisNote];

        buzz(melodyPin, hotlineb_melody[thisNote], noteDuration);

        int pauseBetweenNotes = noteDuration * 1.30;
        delay(pauseBetweenNotes);

        buzz(melodyPin, 0, noteDuration);
      }
    }
  }
  {
    void buzz(int targetPin, long frequency, long length) {
      digitalWrite(13, HIGH);
      long delayValue = 1000000 / frequency / 2;
      long numCycles = frequency * length / 1000;
      for (long i - 0; i < numCycles; i++) {
        digitalWrite(targetPin, HIGH);
        delayMicroseconds(delayValue);
        digitalWrite(targetPin, LOW);
        delayMicroseconds(delayValue);
      }
      digitalWrite(13, LOW);
          }
        }
      }
    }
  }
}

How to fix expected primary expression beforeThe expected primary expression before occurs due to syntax errors. It usually has a character or a keyword at the end that clarifies the cause. Here you’ll get access to the most common syntax mistakes that throw the same error.

Continue reading to see where you might be getting wrong and how you can solve the issue.

Contents

  • Why Does the Expected Primary Expression Before Occur?
    • – You Are Specifying the Data Type With Function Argument
    • – The Wrong Type of Arguments
    • – Issue With the Curly Braces Resulting in Expected Primary Expression Before }
    • – The Parenthesis Following the If Statement Don’t Contain an Expression
  • How To Fix the Given Error?
    • – Remove the Data Type That Precedes the Function Argument
    • – Pass the Arguments of the Expected Data Type
    • – Ensure The Equal Number of Opening and Closing Curly Brackets
    • – Add an Expression in the If Statement Parenthesis
  • FAQ
    • – What Does It Mean When the Error Says “Expected Primary Expression Before Int” in C?
    • – What Is a Primary Expression in C Language?
    • – What Are the Types of Expressions?
  • Conclusion

Why Does the Expected Primary Expression Before Occur?

The expected primary expression before error occurs when your code doesn’t follow the correct syntax. The mistakes pointed out below are the ones that often take place when you are new to programming. However, a programmer in hurry might make the same mistakes.

So, here you go:

– You Are Specifying the Data Type With Function Argument

If your function call contains the data type along with the argument, then you’ll get an error.

Here is the problematic function call:

int addFunction(int num1, int num2)
{
int sum;
sum = num1 + num2;
return sum;
}
int main()
{
int result = addFunction(int 20, int 30);
}

– The Wrong Type of Arguments

Passing the wrong types of arguments can result in the same error. You can not pass a string to a function that accepts an argument of int data type.

int main()
{
int result = addFunction(string “cat”, string “kitten”);
}

– Issue With the Curly Braces Resulting in Expected Primary Expression Before }

Missing a curly bracket or adding an extra curly bracket usually results in the mentioned error.

– The Parenthesis Following the If Statement Don’t Contain an Expression

If the parenthesis in front of the if statement doesn’t contain an expression or the result of an expression, then the code won’t run properly. Consequently, you’ll get the stated error.

How To Fix the Given Error?

You can fix the “expected primary-expression before” error by using the solutions given below:

– Remove the Data Type That Precedes the Function Argument

Remove the data type from the parenthesis while calling a function to solve the error. Here is the correct way to call a function:

int main()
{
int result = addFunction(30, 90);
}

– Pass the Arguments of the Expected Data Type

Double-check the function definition and pass the arguments of the type that matches the data type of the parameters. It will ensure that you pass the correct arguments and kick away the error.

– Ensure The Equal Number of Opening and Closing Curly Brackets

Your program must contain an equal number of opening and closing curly brackets. Begin with carefully observing your code to see where you are doing the mistake.

– Add an Expression in the If Statement Parenthesis

The data inside the parenthesis following the if statement should be either an expression or the result of an expression. Even adding either true or false will solve the issue and eliminate the error.

FAQ

You can view latest topics and suggested topics that’ll help you as a new programmer.

– What Does It Mean When the Error Says “Expected Primary Expression Before Int” in C?

The “expected primary expression before int” error means that you are trying to declare a variable of int data type in the wrong location. It mostly happens when you forget to terminate the previous statement and proceed with declaring another variable.

– What Is a Primary Expression in C Language?

A primary expression is the basic element of a complex expression. The identifiers, literals, constants, names, etc are considered primary expressions in the C programming language.

– What Are the Types of Expressions?

The different types of expressions include arithmetic, character, and logical or relational expressions. An arithmetic expression returns an arithmetic value. A character expression gives back a character value. Similarly, a logical value will be the output of a logical or relational expression.

Conclusion

The above error revolves around syntax mistakes and can be solved easily with a little code investigation. The noteworthy points depicting the solutions have been written below to help you out in removing the error:

  • Never mention the data type of parameters while calling a function
  • Ensure that you pass the correct type of arguments to the given function
  • You should not miss a curly bracket or add an extra one
  • The if statement should always be used with the expressions, expression results, true, or false

What is expected primary expression before errorThe more you learn the syntax and practice coding, the more easily you’ll be able to solve the error.

  • Author
  • Recent Posts

Position is Everything

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

I can’t figure out these errors. Every function call I make in the cpp file gives me these errors:


movie.cpp: In member function ‘void movie::menu(int, movie*)’:
movie.cpp:57: error: expected primary-expression before ‘*’ token
movie.cpp: In member function ‘void movie::enter_movie(movie*)’:
movie.cpp:68: error: expected primary-expression before ‘name’
movie.cpp:69: error: expected primary-expression before ‘int’
movie.cpp:70: error: expected primary-expression before ‘int’
movie.cpp:71: error: expected primary-expression before ‘*’ token
movie.cpp:72: error: expected primary-expression before ‘rating’
movie.cpp:73: error: expected primary-expression before ‘int’
main.cpp: In function ‘int main()’:
main.cpp:29: error: expected primary-expression before ‘int’
main.cpp:29: error: expected primary-expression before ‘*’ token
main.cpp:29: error: expected primary-expression before ‘)’ token

Lines 68-73 correspond to the enter_movie() function. line 29 is for main’s call to the menu function.

class

1
2
3
4
5
6
7
8
9
class movie
{
	private:
                // There's several private members here
	public:
		void menu( int, movie * );
		void enter_movie( movie * );
                // there's several other functions here, their calls can be seen below
};

cpp

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
void movie::menu( int choose, movie *m )
{
	do
	{	
		cout << "Would you like to enter or rent a movie?" << endl;
		cout << "( 1 - enter, 2 - rent, 0 - exit ): ";
		cin >> choose;
		cout << endl;
	}
	while ( choose >= 0 && choose <= 2 );

	if ( choose == 1 )
		m->enter_movie( movie *m ); //supposed to call enter movie function.
	if ( choose == 2 )
		// Enter search mode
	if ( choose == 0 )
		exit(1);
}

void movie::enter_movie( movie *m )
{
	m->set_name( string name );
	m->set_stars( int stars );
	m->set_num_cast( int num_cast );
	m->set_cast( string *cast );
	m->set_rating( string rating );
	m->set_copies( int copies );
        //these functions are the other public member functions, their parameters are the 
        //private member variables.
}

main

1
2
3
4
5
6
7
8
int main()
{
	netflix Netflix;
	movie Movie;
	Movie.menu( int, movie * );

	return 0;
}

I just want to get past these errors at the moment. Also movie * is from the movie class being a private member of another class. I’m guessing I shouldn’t be using it like this although I was told today that I should. I don’t know, I barely know what I’m doing. But if I could get some assistance with these errors I’ll be eternally grateful. :)

Could you indicate what lines on the errors correspond to what lines in your posted code?

oops must have forgotten:
movie.cpp line 57 = cpp line 13
movie.cpp lines 68-73 = lines 22-27
main.cpp line 29 = main line 5

thanks for checking it out :)

Do you know how to call a function? It sounds simple, but it seems the errors are all from the same kind of mistake when calling the function. You might want to read this tutorial, paying close attention to how functions are called in the examples:
http://www.cplusplus.com/doc/tutorial/functions/

Sadly I’ve been reading about functions all day trying to figure out what it is that I’m doing wrong. I read through the tutorial page to just to look for any thing I may have missed. Still I’m finding very little info on properly calling member functions of classes with private variables. That wasn’t covered in the tutorial, or hardly any where that I can find. I tried using the dot (.) instead of the arrow (->) but that made my errors worse.
The way I have them set up now was suggested by a TA. So I don’t really know what else to do, every one I’ve talked to so far has lead me to the code I have but no one’s been able to get past these errors. I’ve been assuming that there’s something horribly wrong with the function call but I just can’t find it.

Your use of . and -> are fine; it is the parameter list that is the issue. Compare that to the tutorial’s example of calling a function and see if you can spot the difference.

So all the examples have parameters that are empty, with variables, with types, or with types and variables. Some use the &. I swear I’ve tried all possible combinations. Unless there’s somehow one Ive missed I honestly don’t see anything different. Also all the examples have quite different parameter set-ups, could you please point out one of the examples that has the difference in it and maybe I could better pinpoint what difference I’m looking for. Thank you. :)

movie.h
lines 6-7: You don’t need to pass a pointer to movie as an argument. A function that is a member of a class implicity has access to the member variables of the class.

movie.cpp
Line 1,20: Ditto.

Line 13: Simply call enter_movie(). You don’t need to pass any arguments.

Lines 22-27: 1) You don’t need the m-> to call member functions of your class. 2) You don’t specify types in a function call. Types are only specified in a functin prototype. 3) Since you haven’t shown these functions, it’s not clear if these functions are prompting for input. If they are, you don’t need arguments at all.

main.cpp
line 5: 1) You have to pass an integer value, not a type. Again, you don’t specify types in a function call. 2) movie * is a type. You don’t need this argument since the instance of movie is specified by the Movie variable.

You are confusing two concepts:

1. Declaring and defining functions and members of classes.

2. Calling functions and members of classes ( whether you call a class member on an object or a static member on a class)

When you define a function, you have to add the type of the parameter:

1
2
3
int sum( int number1, int number2) {
    return number1 + number2;
}

Now I want to use the function I wrote:

1
2
3
4
5

int main(void) {
    std::cout << sum( 1, 2) << std::endl;
}

What you do wrong in the main function:

1
2
3
4
5
6
7
8
int main()
{
	netflix Netflix;
	movie Movie;
	Movie.menu( int, movie * );

	return 0;
}

Is calling the member function with types, instead of values or variables. Try this:

1
2
3
4
5
6
7
8
9
int main()
{
	netflix Netflix;
	movie Movie;
        movie *pointerToMovieObject = new movie();
	Movie.menu( 3, pointerToMovieObject );

	return 0;
}

Post the entire code when you’re done.
I will help you out with your code

Alrighty, it took a mix of both you guys advice but I’m down to just one error:


movie.cpp:42: error: variable or field ‘menu’ declared void

42 in my code is line 1 above.

I took out the pointers and the m->. I took out the parameters of all the function calls with two exceptions. Main line 5 and movie.cpp line 1 have a 0 in them and that’s it. Also in movie.cpp line 20 it’s now just void movie::enter_movie( movie ). It wouldn’t let me take it out or it got mad at me. I don’t really know why I need the number in the two function calls to get rid of so many errors. I tried just declaring the function in the class without any parameters at all since I was asking for the number inside the function but it got mad at me for that too. Feels like c++ is just out to get me. I do things that seem logical to me but the compiler blows up overtime I try something. Anyways, any clues on that last error? :)

Last edited on

@mt106250
Hi didn’t see your post there till just now, I’ll post it here in a bit. I’ll warn you it’s long, but thank you for helping:)

@andres81

There are a few problems with the code you posted:
main.cpp
Line 5: There is no reason to dynamically allocate an instance of movie.
Line 6: As I pointed out before, there is no reason to pass a pointer to a movie instance assuming all the OP wants to do is update a single instance (Movie).
Line 7: You have a memory leak. The instance of movie that was dynamically allocated was never released.

@OP

It wouldn’t let me take it out or it got mad at me. I don’t really know why I need the number in the two function calls to get rid of so many errors.

In movie.cpp line 1, you’re passing choose as an argument. There is really no need for choose to be an argument since you prompt for it at line 7. However, if you remove choose as an argument, you must declare it locally within menu().

Last edited on

Ok here’s the whole thing, maybe that will clear any confusion of what I’ve attempted to do. Also there’s several blank functions that I just haven’t even gotten to yet because I either don’t know what I’m supposed to use it for or I’m waiting to get past these errors before I get into them. Figured I’d get past the current errors before I start making more. :)

net header

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
#ifndef NETFLIX_H
#define NETFLIX_H
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include "./movie.h"


class netflix
{

	private:
		movie *m;
		int num_movies;

	public:
		netflix();
		netflix( const netflix & );
		~netflix();
		void set_movie( movie * );
		void set_num_movies( int );
		movie get_movie();
		int get_num_movies();

};

#endif 

net.cpp

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
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include "./netflix.h"

using std::cout;
using std::cin;
using std::endl;
using std::string;

netflix::netflix()
{

	m = NULL;
	num_movies = 0;

}

netflix::~netflix()
{

	delete [] m;
	m = NULL;

}

netflix::netflix( const netflix & ){}

void netflix::set_num_movies( int ){}

movie netflix::get_movie() { return *m; }
int netflix::get_num_movies() { return num_movies; }

movie header

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
#ifndef MOVIE_H
#define MOVIE_H
#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>

using std::string;

class movie
{

	private:
		string name;
		int stars;
		int num_cast;
		string *cast;
		string rating;
		int copies;

	public:
		movie();
		~movie();
		movie( const movie & );
		void menu( int );
		void enter_movie( movie );
		void set_name( string );
		void set_stars( int );
		void set_num_cast( int );
		void set_cast( string * );
		void set_rating( string );
		void set_copies( int );
		string get_name();
		int get_stars();
		int get_num_cast();
		string get_cast();
		string get_rating();
		int get_copies();

};

#endif 

movie.cpp

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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include "./movie.h"

using std::cout;
using std::cin;
using std::endl;
using std::string;

movie::movie()
{

	stars = 0;
	num_cast = 0;
	cast = NULL;
	copies = 0;

}

movie::~movie()
{

	delete [] cast;
	cast = NULL;

}

movie::movie( const movie & ){}

void movie::menu( 0 )
{

	int choose;

	do
	{
	
		cout << "Would you like to enter or rent a movie?" << endl;
		cout << "( 1 - enter, 2 - rent, 3 - exit ): ";
		cin >> choose;
		cout << endl;
	
	}
	while ( choose >= 1 && choose <= 3 );

	if ( choose == 1 )
		enter_movie();
	if ( choose == 2 )
		// Enter search mode
	if ( choose == 3 )
		exit(1);

}

void movie::enter_movie( movie )
{

	set_name();
	set_stars();
	set_num_cast();
	set_cast();
	set_rating();
	set_copies();

}

void movie::set_name( string )
{

	cout << "Movie title: ";
	getline( cin, name );

}

void movie::set_stars( int )
{

	cout << "Number of stars: ";
	cin >> stars;

}

void movie::set_num_cast( int )
{

	cout << "Number of cast members: ";
	cin >> num_cast;

}

void movie::set_cast( string * )
{

	for ( int i = 0; i < num_cast; ++i )
	{
	
		cout << "Cast member #" << i << ": ";
		getline( cin, *cast );
	
	}

}

void movie::set_rating( string )
{

	cout << "Rating: ";
	getline( cin, rating );

}

void movie::set_copies( int )
{

	cout << "Number of copies: ";
	cin >> copies;

}

string movie::get_name() { return name; }
int movie::get_stars() { return stars; }
int movie::get_num_cast() { return num_cast; }
string movie::get_cast() { return *cast; }
string movie::get_rating() { return rating; }
int movie::get_copies() { return copies; }

main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include "./netflix.h"
#include "./movie.h"

using namespace std;

//void menu();

int main()
{

//	menu( int );

	netflix Netflix;
	movie Movie;
	movie *m = new movie();
	Movie.menu( 0 );

	return 0;

}

output: refers to line 32 in this post.


movie.cpp:42: error: variable or field ‘menu’ declared void

I’m sorry if the things I’ve done in this code are just ridiculous. I’m amazingly terrible at coding despite spending all of my free time reading the 2 books I have and going to TA office hours. I took me a week just to figure out how to begin designing the thing and it’s been a week of me being stuck at this point. Seems like every thing I do make it worse. I am dying to understand this stuff so any thing you can say to help will be greatly appreciated. Thank you much. :)

movie.cpp line 32: get rid of the 0. This function should not have any arguments. 0 is not valid in an argument list.

main.cpp line 19: get rid of this line. There is no reason to dynamically allocate a move instance. It’s also causing a memory leak since you never delete it.

main.cpp line 20: get rid of the 0. You can’t pass a 0 to a function that doesn’t take any arguments.

movie.cpp line 30: If you’re going to pass an argument here, you need to name the argument.

Line 57, 69, 77, 85, 93, 106, 114: Again, if you’re going to pass and argument to these functions, you need to specify a name, not just a type. You can get away with not specifying a name in the declaration, but a name is required in the definition. However, I don’t see that you need any of these arguments.

movie.h line 17: Why is cast a pointer? In movie.cpp line 100, you’re trying to do a getline to a null pointer. That’s going to cause a trap or an exception.

I’m assuming your intention here is to allow multiple cast members. If that’s what you’re trying to do, you should use a vector:

1
2
3
4
5
6
    vector<string>  cast;
...
// In movie::set_cast
   string cast_member;
   getline (cin, cast_member);
   cast.push_back (cast_member);

Likewise in netflix.h, I assume your intent with the movie pointer is to allow multiple movies. Again you should use a vector.

1
2
3
4
  vector<movie>  movies;
...
  // In netflix::set_movie you should be passing movie by reference
  movies.push_back (movie);

Last edited on

hmm, I made all the recommended changes. These are my new errors:


In file included from ./netflix.h:18,
                 from netflix.cpp:15:
././movie.h:28: error: ISO C++ forbids declaration of ‘vector’ with no type
././movie.h:28: error: expected ‘;’ before ‘<’ token
In file included from netflix.cpp:15:
./netflix.h:25: error: ISO C++ forbids declaration of ‘vector’ with no type
./netflix.h:25: error: expected ‘;’ before ‘<’ token
netflix.cpp: In constructor ‘netflix::netflix()’:
netflix.cpp:25: error: ‘m’ was not declared in this scope
netflix.cpp: In destructor ‘netflix::~netflix()’:
netflix.cpp:33: error: ‘m’ was not declared in this scope
netflix.cpp: At global scope:
netflix.cpp:40: error: prototype for ‘void netflix::set_movie()’ does not match any in class ‘netflix’
./netflix.h:33: error: candidate is: void netflix::set_movie(movie*)
netflix.cpp: In member function ‘movie netflix::get_movie()’:
netflix.cpp:44: error: ‘m’ was not declared in this scope
In file included from movie.cpp:15:
./movie.h:28: error: ISO C++ forbids declaration of ‘vector’ with no type
./movie.h:28: error: expected ‘;’ before ‘<’ token
movie.cpp: In constructor ‘movie::movie()’:
movie.cpp:27: error: ‘cast’ was not declared in this scope
movie.cpp: In destructor ‘movie::~movie()’:
movie.cpp:35: error: ‘cast’ was not declared in this scope
movie.cpp: At global scope:
movie.cpp:42: error: prototype for ‘void movie::menu()’ does not match any in class ‘movie’
./movie.h:37: error: candidate is: void movie::menu(int)
movie.cpp:67: error: prototype for ‘void movie::enter_movie()’ does not match any in class ‘movie’
./movie.h:38: error: candidate is: void movie::enter_movie(movie)
movie.cpp:79: error: prototype for ‘void movie::set_name()’ does not match any in class ‘movie’
./movie.h:39: error: candidate is: void movie::set_name(std::string)
movie.cpp:87: error: prototype for ‘void movie::set_stars()’ does not match any in class ‘movie’
./movie.h:40: error: candidate is: void movie::set_stars(int)
movie.cpp:95: error: prototype for ‘void movie::set_num_cast()’ does not match any in class ‘movie’
./movie.h:41: error: candidate is: void movie::set_num_cast(int)
movie.cpp:103: error: prototype for ‘void movie::set_cast()’ does not match any in class ‘movie’
./movie.h:42: error: candidate is: void movie::set_cast(std::string*)
movie.cpp:119: error: prototype for ‘void movie::set_rating()’ does not match any in class ‘movie’
./movie.h:43: error: candidate is: void movie::set_rating(std::string)
movie.cpp:127: error: prototype for ‘void movie::set_copies()’ does not match any in class ‘movie’
./movie.h:44: error: candidate is: void movie::set_copies(int)
movie.cpp: In member function ‘std::string movie::get_cast()’:
movie.cpp:138: error: ‘cast’ was not declared in this scope
In file included from ./netflix.h:18,
                 from main.cpp:15:
././movie.h:28: error: ISO C++ forbids declaration of ‘vector’ with no type
././movie.h:28: error: expected ‘;’ before ‘<’ token
In file included from main.cpp:15:
./netflix.h:25: error: ISO C++ forbids declaration of ‘vector’ with no type
./netflix.h:25: error: expected ‘;’ before ‘<’ token
main.cpp: In function ‘int main()’:
main.cpp:29: error: no matching function for call to ‘movie::menu()’
././movie.h:37: note: candidates are: void movie::menu(int)

There’s a lot of errors in here that I previously had, but now theres even more. :(
I was sure to add the #include <vector> . Other than that, not sure.

Why dont you place your netflix header and movie header together?
Along with netflix.cpp and movie.cpp

That’s actually how I had it originally, but it’s required that everything be separate. It’s dumb, I hate it, don’t understand why it has to be this way. I would totally prefer to just have everything in one file. As it is I have to have 5 terminal windows open at once so I can see everything. It really bums me out. :)

That’s understandable.

I think what you should do is work on your other functions, that way you can fix all your errors

If your entire program compiles, post your program so we adjust things more!

Понравилась статья? Поделить с друзьями:
  • Error lvalue required as unary operand
  • Error lvalue required as left operand of assignment перевод
  • Error lvalue required as increment operand
  • Error lvalue required as decrement operand
  • Error lucky block