w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Reading integers from an unorganized text file
I think the following should do what you want (untested code): int c; while ((fin >> std::ws, c = fin.peek()) != EOF) { if (is_digit(c)) { int n; fin >> n; std::cout << n << std::endl; } else { std::string s; fin >> s; } }

Categories : C++

android separating a text file
I think you are facing problem in distinguishing between each lines that are read-out from file. In order to read the file line-by-line you should change your code as below: InputStream fs = getResources().openRawResource(R.raw.treasureclass); BufferedReader br = new BufferedReader(new InputStreamReader(fs)); String line = null; while((line = br.readLine()) != null){ Log.i("line", line); //split the content of 'line' and save them in your desired way }

Categories : Android

mmap reading stale array of integers from an file
The ACSII value of the text is getting printed. Your text seems like: 510 20 30... From ASCII table (to explain what I want to tell): No. ASCII (hex) Space -> 20 0 -> 30 1 -> 31 2 -> 32 3 -> 33 5 -> 35 int is 4 byte in size, so, taking first 4 bytes: Converting to ASCII, "510 " gives "35 31 30 20" in memory which is 0x20303135 (540029237 as decimal) for a little endian machine. Similarly, next 4 bytes "20 3" gives 0x33203032(857747506 as decimal). This is what you are getting. You need to convert each ACSII to integer using atoi() or similar, in this case. But you may store your integers as their binary value itself rather than keeping it as ASCII. The file will not be human readable but it will do your purpose.

Categories : C++

Input text file - swapping integers
I cannot figure out why your code does not work, but i can write a simple extension method to do the swap, something like: Imports System.Runtime.CompilerServices Public Class StringTest Implements ITestable Public Sub ExecuteTest() Implements ITestable.ExecuteTest Dim theString = "00201305170013333" Console.WriteLine("old: " & theString) Dim chars = theString.ToArray() chars.Swap(2, 6) chars.Swap(3, 7) theString = String.Concat(chars) Console.WriteLine("new: " & theString) End Sub End Class Public Module Extensions <Extension()> Public Sub Swap(Of T)(records As IList(Of T), idx1 As Integer, idx2 As Integer) Dim item1 = records.ElementAt(idx1) records(idx1) = records.ElementAt(idx

Categories : Vb.Net

BufferedReader reading online text file without caching text in file?
If you use URLConnection you can use useCaches. Take a look at that link. sample: URL url = new URL("http://www.standarized.com/ads/Test.txt"); URLConnection urlConnection = url.openConnection(); urlConnection.setUseCaches(false); try { // Read all the text returned by the server BufferedReader in = new BufferedReader(new InputStreamReader( urlConnection.getInputStream())); String str; while ((str = in.readLine()) != null) { // str is one line of text; readLine() strips the newline // character(s) inputLine = inputLine + str; } finally { in.close(); }

Categories : Android

Reading a text file of student names and text scores and finding an average
Oops: int i =Integer.parseInt ("TS"); This doesn't make sense. What number is "TS" supposed to represent? Edit: you state: I know that TS is not a valid number that's why I was trying to cast it to a number You can't "cast" letters to a number, again it makes no sense. You need to read in the Strings in the file and then parse those Strings, not some letters you make up. What your code should do is: read in each line in the file in a for loop inside this loop, split the String using String's split(" ") method. Use Integer.parse(...) to parse the 3rd item in the array returned. So would I use Integer.parse(String [] TS)? No, this won't even compile since you're trying to pass a String array into a method that takes a String parameter.

Categories : Java

Reading exact columns of a text file and putting the values/text into a vector
Read a line in. Scan it for the various parts (numbers, first name, middle initial, last name, etc.) Put the elements into a structure that holds all of them. Put pointers to the structures in an array. Using one or more elements as keys, sort the structures as needed.

Categories : C

VB Reading from text file, searching text and feeding to excel
Since i don't know how you are creating the excel-file (EPPlus, Interop, etc), i show you one way to get all substrings after the =: Dim allData = From line In File.ReadLines("Your Path") Where line.TrimStart.StartsWith("MTV") OrElse line.TrimStart.StartsWith("MTB") Let index = line.LastIndexOf("=") Where index >= 0 Select line.Substring(index + 1)

Categories : Vb.Net

PHP Reading in a text file using explode() to get specific parts of text
Please don't do this this way. If you want to use text files (for a small app that's OK) then use a sensible text format. Do away with all these custom delimiters and just use CSV format (where you can use fgetcsv() to read a line into an array), or better, use JSON format with proper tags (use json_decode() to unpack it) and your trouble in extracting times will evaporate. You also don't need all that malarkey extracting dates - look up DateTime::createFromFormat() and make life easy on yourself.

Categories : PHP

reading text file and assigning strings from file to variables
When you call read() in the condition of the while loop, the "cursor" of the BufferedReader advances one character. You don't want to do this to check if the stream can be read, you want to use the ready() method.

Categories : Java

c# reading from a text file
What is going wrong, is that sr.ReadLine() will be executed regardless of whether the document has a next line or not, so it might return null (if you've run out of lines) Simply check whether sr.ReadLine() returns null public void Read(string filename, List<Person> person) { using (StreamReader sr = new StreamReader(filename)) { sr.ReadLine(); sr.ReadLine(); while (!sr.EndOfStream) { String FirstName = sr.ReadLine() ?? "-not defined-"; String LastName = sr.ReadLine() ?? "-not defined-"; person.Add(new Person(FirstName, LastName)); } } }

Categories : C#

Reading From Text File In c++
For C++03, ifstream takes const char* parameter, you could try: ifstream text(file_name.c_str()); While with C++11, your first statement should work.

Categories : C++

Reading integers from Txt and summarize it
The problem is that when the execution of the program reaches line 60, the input for the scanner is "exhausted". You should re-initialize the file variable (recommend you to rename it to scanner or similar) just before beginning with the do- cycle. Not quite sure of the logic of the application, especially whether the do- cycle should be inside the while- cycle or not, but I would recommend you to use brackets even if the control structure has only one statement. This you will outline your intention better and will reduce the possibility for errors which are hard to find.

Categories : Java

Reading data from text file vba
If you want each subfolder's data to be in a separate workbook, then you need to move your new_workbook definition inside your For Each obj_sub_folder loop, and also close that workbook after saving: Set objfso = CreateObject("Scripting.FilesystemObject") Set objfolder = objfso.getfolder("Z: est") i = 1 For Each obj_sub_folder In objfolder.subfolders Set new_workbook = Workbooks.Add i = 1 ReadData = "" For Each objfile In obj_sub_folder.Files Set current_worksheet = new_workbook.Worksheets.Add current_worksheet.Name = objfile.Name filestream = FreeFile() path = "Z: est" & obj_sub_folder.Name & "" & objfile.Name Open path For Input As #filestream Do Until EOF(filestream) Input #filestream, ReadData

Categories : Excel

Reading from a text file in Java
You should use FileUtils to do this. It has a method named readLines public static List<String> readLines(File file, Charset encoding) throws IOException Reads the contents of a file line by line to a List of Strings. The file is always closed. See @BackSlash's comment above to see how you're using InputStream.read() wrong. @BackSlash also mentioned you can use java.nio.file.Files#readAllLines but only if you're using Java 1.7 or later.

Categories : Java

OutOfMemoryError from reading a text file
def lines = [] In groovy, this creates an ArrayList<E> with size 0 and no preallocation of the internal Object[]. When adding items, if capacity is reached, a new ArrayList is created. The larger the list, the more time spent reallocating a new list to accommodate new entries. I suspect that's where your memory issue occurs because, although I'm not exactly sure how ArrayList allocates a new list, if you're getting OOM for a relatively small data set, that's where I'd look first. For 100,000 entries, you create a new list roughly 29 times (assuming expansion factor of 1.5) when starting with an empty ArrayList. If you have a general idea how large the list needs to be, just set the initial capacity, doing so avoids all the reallocating nonsense; see if this works: def lines = ne

Categories : Java

reading row from text file into two vectors c++
With operator[] you can only access existing elements. Going out of bounds invokes undefined behaviour. Your vectors are empty and you need to use push_back method to add elements to them. Second problem is while (!file.eof()) anti-pattern. It'll typicaly loop one to many times because the read of last record doesn't neccesarily trigger eof. When reading from streams, always check whether input succeeded before you make use of values read. That's typicaly done by using operator>> inside loop condition. string temp_s; int temp_i; while (input_file >> temp_s >> temp_i) { players.push_back(temp_s); balances.push_back(temp_i); } This way the loop stops if operator>> fails.

Categories : C++

Reading each line of a text file into VB
you could open the list in Excel, so that all the data to be manipulated goes into Column A, then use formulas as below to create your UNIX commands in Columns B, C, D: FIRST Command: ="grep -i " &LOWER(LEFT(A:A,FIND(" ",A:A))) & " */*.cfg" SECOND Command: ="grep -i "&LOWER(LEFT(TRIM(MID(A:A,FIND(" ",A:A),LEN(A:A))),FIND(" ",TRIM(MID(A:A,FIND(" ",A:A),LEN(A:A))))))&" */*.cfg" THIRD Command: ="grep -i "&LOWER(MID(RIGHT(A:A,LEN(A:A)-FIND(" ",A:A)),FIND(" ",RIGHT(A:A,LEN(A:A)-FIND(" ",A:A))),LEN(RIGHT(A:A,LEN(A:A)-FIND(" ",A:A)))))&" */*.cfg" Once you have got all your texdt to be manipulated in Column A, copy down the formulas in columns B,C,D then you could run the below code (may need tweaking) to create your output: Sub getCommands() Dim oFso As New

Categories : Excel

Reading an embedded text file
Assuming you mean that you have a file in your project that you've set as an EmbeddedResource, you want using (var stream = Assembly.GetExecutingAssembly() .GetManifestResourceStream(path)) { ... } where path should be the assembly name followed by the relative path to your file in the project folder hierarchy. The separator character used is the period .. So if you have an assembly called MyCompany.MyProject and then in that project you have a folder Test containing Image.jpg, you would use the path MyCompany.MyProject.Test.Image.jpg to get a Stream for it.

Categories : C#

Reading delimited text file?
i don't know exactly what do you need, but you can do this: if you have string str with the whole text in it you can do string[] lines = str.Split(' ');// split it to lines; and then for each line you can do string[] cells = line.Split('|');// split a line to cells if we take it to the next level we can do: public class line { public int ItemNumber { get; set; } public string ProductStatus { get; set; } public int UPC { get; set; } public line(string currLine) { string[] cells = currLine.Split('|'); int item; if(int.TryParse(cells[0], out item)) { ItemNumber = item; } ProductStatus = cells[1]; int upc; if (int.TryParse(cells[2], out upc)) { UPC = upc; } } } and then: string[] lines = str.Substring(s

Categories : C#

Reading from a CSV/text file with quotes in C++
The following works with the given input: a,b,c,"a,b,c","a,b",d,e,f #include <iostream> #include <sstream> #include <string> using namespace std; int main() { std::string line; while(std::getline(cin, line, '"')) { std::stringstream ss(line); while(std::getline(ss, line, ',')) { cout << line << endl; } if(std::getline(cin, line, '"')) { cout << line; } } }

Categories : C++

Matlab not reading text file
From the details you provided about the shape of your text-file I'm guessing it has the following form : label1 info1 text1 1 1.1 3.1 label2 info2 text2 2 2.1 3.2 lebel3 info3 text3 3 3.1 3.3 ... You can load all this data using a loop and the fscanf function and simple loops. If N is the number of lines of your text-file the following code might work for you: f=fopen('test.txt'); for k=1:N for i=1:3 a{k,i} = fscanf(f,'%s',1); end b(k,:) = fscanf(f,['%f' '%f' '%f'],3); end fclose(f); Then you will have one cell-array of strings a: a = 'label1' 'info1' 'text1' 'label2' 'info2' 'text2' 'lebel3' 'info3' 'text3' And one array with numeric data b: b = 1.0000 1.1000 3.1000 2.0000 2.1000 3.2

Categories : Matlab

Reading data from a text file with Go
The Rubber duck debugging effect worked again. After asking the question, I found out the answer by my self. Here it is in case other people share the same problem I had. In the following example I'll simply print out the data read import ( "bufio" "fmt" "log" "os" "strings" ) func loadFile( fileName string ) { // Open file and instantiate a reader file, err := os.Open(fileName) if err != nil { log.Fatal(err) } reader := bufio.NewReader(file) var { value0 uint64, nbrRows uint16 } // Read header values if _,err := fmt.Fscanf(reader, "%d %d ", &value0, &nbrRows); err != nil { log.Fatal(err) } // Iterate on the rows for i := uint16(0); i < nbrRows; i++ { var {

Categories : Go

Reading to text file from MySQL
You do not seem to put into the database the things that the column names describe? fileName and time are for example both set to a timestamp, and clientName is set to the contents of the file. When you later try to select based on clientName, you are actually selecting based on the contents of the file. Furthermore, when reading the data, you are reading the blob data from the column fileName, but this is wrong because: fileName contains new Date().toString(), not the contents of the file fileName should surely contain the file's name, not its contents?

Categories : Java

Reading from a text file in matlab
Open the file, and read each column with the appropriate conversion specifier. fileID = fopen('scan1.txt'); C = textscan(fileID, '%s %s %f32 %d8 %u %f %f %s %f'); fclose(fileID); celldisp(C) see it: Documentation Center

Categories : Matlab

reading a text file into an array
Here's the beauty of C: You can read the file in a single operation, and save yourself the looping: Something like fread(myArray, sizeof(myArray), myfile) You should probably initialize the array to all zeros before you do this, though: char myArray[26][26] = { 0 }; Or fill it with zeroes if you don't initialize it: memset(myArray, 0, sizeof(myArray)); Also, you might want to print a newline (" ") at the end of each outer loop in your printing section: otherwise the file contents will appear as one long, continuous string.

Categories : C

Difficulty Reading Text from Excel file
You can't look if L (which is a list) is in L1. You can look to see if the items in L are in L1. For example: >>> s = 'abcde' >>> b = ['a', 'f', 'g', 'b'] >>> b ['a', 'f', 'g', 'b'] >>> for i in b: ... if i in s: ... print i ... else: ... print "nope" ... a nope nope b >>> If you have two lists, you'll need to loop over both, with a nested for loop: for i in b: for j in L1: do stuff Hope that gives you a start. ETA: You can use enumerate to get the index of the item you're looping on currently and use that to get into the right row in the second list: >>> b = ['a', 'f', 'g', 'b'] >>> L1 = ['worda', 'words including b', 'many many words', 'a lot more words'] >>> for i, j in enumerate(b):

Categories : Excel

Reading a particular line from a text file in Java
here is how you do it: import java.io.*; public class Test { public static void main(String [] args) { // The name of the file to open. String fileName = "temp.txt"; int counter = 0; // This will reference one line at a time String line = null; FileReader fileReader = null; try { // FileReader reads text files in the default encoding. fileReader = new FileReader(fileName); // Always wrap FileReader in BufferedReader. BufferedReader bufferedReader = new BufferedReader(fileReader); while((line = bufferedReader.readLine()) != null) { counter++; if(counter == 3 || counter == 8 || counter == 12) { // do your code } }

Categories : Java

Reading in matrix from text file and displaying
The first number you scan is the number of items on each line, but in the file the first line is a 1 and not 5 so it reads only one extra number. The file should probably look like this: 25 1 2 3 4 5 5 4 3 2 1 1 2 3 4 5 5 4 3 2 1 1 2 3 4 5 Or if it's fixed sizes, why read the number or items from the file at all?

Categories : C++

Reading a formatted text file in java
Use the below code to format the string in java import java.util.StringTokenizer; public class Test { public static void main(String args[]) { String str="0:1 0:0 1:1 2:2 3:3"; format(str); } public static void format(String str) { StringTokenizer tokens=new StringTokenizer(str, " "); // Use Space as a Token while(tokens.hasMoreTokens()) { String token=tokens.nextToken(); String[] splitWithColon=token.split(":"); System.out.println(splitWithColon[0] +" "+splitWithColon[1]); } } } Output of Code : 0 1 0 0 1 1 2 2 3 3

Categories : Java

Issue reading text file into matrix
Does really this take part of your input file ? Object data Format 6 If so, just skip those lines like this: char s[10]; infile.getline(s, 5); infile.getline(s, 5); I used the char array "s" to copy that first 5 character from the entire row to it. When you call getline() the reader loads all the line, so no matter how much of that row you read, it all be skipped. And make sure you declared so you can use the getline function. #include <string.h> And please let me know if I helped you.

Categories : C++

Java delimiter reading a text file
I suggest you to use bufferedreader instead of scanner. You can use below code : BufferedReader br=new BufferedReader(new FileReader("your file name")); br.readLine(); //it will omit first line Array x String x=br.readLine(); //it return second line as a string String[] x_value=x.split(","); //You can parse string array into int. This is for Array x. You can do the same for array y. and after that parse into int.

Categories : Java

Windows Store App reading from text file
You can read the file into a string collection using ReadLinesAsync: try { var file = await folder.GetFileAsync(path); var lines = await FileIO.ReadLinesAsync(file); foreach (string line in lines) { // "line" variable should contain "account(x) string(x)" // You can then parse it here.. } } ...

Categories : C#

Infinite-loop when reading from a text file
The simple fix is to change all your a != ' ' to a != EOF && a != ' ' There are many other fixes that also ought to be made, but that should fix the problem. As a general rule, you should do while( (a=fgetc(fp))!=EOF) {...} instead of do/while, since it helps avoid this particular error and is far more idiomatic. Also, do not use feof as you are. The purpose if feof is to distinguish between having reached the end of the data and having encountered a read error. Since you are not dealing with read errors at all in your code, there is no point in invoking feof. (Note that if you do encounter a read error, feof will always return false and you will again be in an infinite loop.)

Categories : C

Reading in text file with unmatched quotes
Your idea of looking for quotes next to a comma is probably the best thing you can do; you could however try to turn it around and have the regex escape all the quotes that are not next to a comma (or start/end of line): Search for (?<!^|,)"(?!,|$) and replace all the matches with "". R might not be the best tool for this because its regex engine doesn't have a multiline mode, but in Perl it would be a one-liner: $subject =~ s/(?<!^|,)"(?!,|$)/""/mg;

Categories : R

Bugs in reading and writing to text file
In the writer method you're closing the file output stream: fos.close(); But surely you should be closing the print stream instead. prntst.close(); Closing the print stream will flush the stream and then close the underlying output stream. When you close the output stream, it won't know anything about the print stream constructed on top of it, so won't know to flush it.

Categories : Java

error while reading a text file in ruby
Write it as: def read_file_info(file_name) arr = IO.readlines(file_name) puts arr end read_file_info("abcd.txt") This is what happened when you pass "abcd.txt" to the method. *file_name creates an array: def read_file_info(*file_name) p file_name end read_file_info("abcd.txt") # >> ["abcd.txt"] IO.readlines(file_name) expects a single file name as a string, but you gave it an Array, which, in turn, gave you the error: no implicit conversion of Array into String (TypeError) If you want to use *file_name then, inside the method, use Array#[] to give your IO.readlines method a single file at a time as a string.

Categories : Ruby

Reading numbers from a text file to an array
It's simple, when you get the ASCII code you can easily convert it to the digit you want, suppose you read a character (char ) from the file its '0', '1', '2', ... or '9' and you want the int value, you simple convert the char to int and subtract integer value of '0' which is 48. Like This: char ch = x.Read(); int chIntValue = ((int)ch) - 48; But almost all the modern programming languages have a ReadInt, GetInteger method or something like that in the io libraries they provide.

Categories : C#

Reading a large text file in parallel in C++
I suggest you use something like fread to read many lines into a buffer and then operate on the buffer in parallel. http://www.cplusplus.com/reference/cstdio/fread/ I once read an image one pixel (int) at a time, did a conversion to the pixel and then wrote the value to a buffer. That took well over 1 minute for a large file. When i instead used fread to read the whole file into a buffer first and then do the conversion on the buffer in memory it took less than one second for the whole operation. That's a huge improvement without using any parallelism. Since your file is so large you can read it in in chucks, operate on the chunk in parallel and then read in the next chuck. You could even read the next chuck (with one thread) while you're processing the previous chuck in parallel

Categories : C++

Reading from a text file and then using the input with in the program
You can use std::getline function to get one line at a time. It looks like this: std::string strLine; int nCount = 0; while (std::getline(infile, strLine)) { stu_answers[nCount++] = strLine.at(0); } Then nCount will be the answer number.

Categories : C++



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.