Golang Scanf示例

说明

golang scanf示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: fmt

示例#1
文件: poisonous_plants.go 项目: yaru22/problem-solving

func main() {
	var n int
	fmt.Scanf("%d\n", &n)
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &arr[i])
	}
	var i, j, l, cnt int
	arrLen := n
	for cnt = 0; ; cnt++ {
		j = 0
		for i, l = 1, arrLen; i < l; i++ {
			if arr[i-1] >= arr[i] {
				j++
				arr[j] = arr[i]
			}
		}
		if i == j+1 {
			fmt.Println(cnt)
			break
		}
		arrLen = j + 1
	}

}

示例#2
文件: kdtree.go 项目: iyoo14/goalgo

func main() {
	var x, y int

	fmt.Scanf("%d", &N)
	P = make(Ps, N)
	for i := 0; i < N; i++ {
		fmt.Scanf("%d %d", &x, &y)
		P[i] = NewPoint(i, x, y)
		T[i].l = NIL
		T[i].r = NIL
		T[i].p = NIL
	}
	np = 0
	root := makeKDTree(0, N, 0)

	log.Println(P)
	log.Println(T)
	var q int
	fmt.Scanf("%d", &q)
	var sx, tx, sy, ty int
	for i := 0; i < q; i++ {
		fmt.Scanf("%d %d %d %d", &sx, &tx, &sy, &ty)
		ans := lib.NewVector(N)
		log.Println(ans)
		find(root, sx, tx, sy, ty, 0, ans)
		for j := 0; j < ans.Size(); j++ {
			an := ans.V[j]
			ap := an.(Point)
			ap.disp()
		}
	}
}

示例#3
文件: solution.go 项目: mohan08p/Competitive_Programming

func main() {
	var T int
	fmt.Scanf("%d", &T)
	for t := 0; t < T; t++ {
		var N int
		fmt.Scanf("%d", &N)
		var no5, no3 = 0, 0
		for i := N / 3; i >= 0; i-- {
			if (N-3*i)%5 == 0 {
				no3 = i
				no5 = (N - 3*i) / 5
				break
			}
		}
		if no3 == 0 && no5 == 0 {
			fmt.Println("-1")
		} else {
			for i := 0; i < 3*no3; i++ {
				fmt.Print("5")
			}
			for i := 0; i < 5*no5; i++ {
				fmt.Print("3")
			}
			fmt.Println()
		}
	}
}

示例#4
文件: init.go 项目: iopred/discord-cli

//SetChannelState sets the Channel inside the State
func SetChannelState(dg *discordgo.Session) {
	State.InsertMode = false

	guild := State.Guild
	d := color.New(color.FgYellow, color.Bold)
	d.Printf("Select a Channel:\n")
	for key, channel := range guild.Channels {
		if channel.Type == "text" {
			fmt.Printf("%d:%s\n", key, channel.Name)
		}
	}

	var response int
	fmt.Scanf("%d\n", &response)
	for guild.Channels[response].Type != "text" {
		Error := color.New(color.FgRed, color.Bold)
		Error.Printf("That's a voice channel, you know this is a CLI right?\n")
		d.Printf("Select a Channel:\n")
		fmt.Scanf("%d\n", &response)
	}

	State.Channel = guild.Channels[response]

	Clear()

	State.InsertMode = true
}

示例#5
文件: B.go 项目: BanSheeGun/Gun

func main() {
	var n int64
	var ans, m, t, i int64
	var a [200]int64
	fmt.Scanf("%v\n", &n)
	for i = 1; i <= n; i++ {
		fmt.Scanf("%v", &a[i])
	}

	t = 1
	ans = 1
	for a[t] == 0 {
		t = t + 1
		if t == n+2 {
			ans = 0
			break
		}
	}
	m = 0
	for i = t; i <= n; i++ {
		if a[i] == 1 {
			ans = ans * (m + 1)
			m = 0
		} else {
			m = m + 1
		}
	}
	fmt.Println(ans)
}

示例#6
文件: euler_067.go 项目: telmojsneves/hackerrank

func main() {

	var t, n int
	var result int
	var num int

	fmt.Scanf("%d", &t)

	for ; t != 0; t-- {
		fmt.Scanf("%d", &n)
		for i := 0; i < n; i++ {
			for j := 0; j <= i; j++ {

				fmt.Scanf("%d", &num)
				matrix[i][j] = num

			}
		}

		result = bottomUp(n - 1)

		fmt.Println(result)

	}
	//Enter your code here. Read input from STDIN. Print output to STDOUT
}

示例#7
文件: insertionSort.go 项目: rhatdan/Algorithms

func main() {

	var (
		myList []int
		choice int
		num    int
	)

	fmt.Println("Enter a list of numbers to be sorted, after each input you ll be prompted with a choice {continue(1)/quit(0)}")

	for {
		fmt.Println("Enter a number")
		if _, err := fmt.Scanf("%d", &num); err != nil {
			log.Fatalln(err)
		}
		myList = append(myList, num)
		fmt.Println("Do you wish to continue or quit")
		if _, err := fmt.Scanf("%d", &choice); err == nil {
			if choice == 1 {
				continue
			} else {
				break
			}
		}
	}

	insertionSort(myList)

}

示例#8
文件: elementary9-guess.go 项目: roessland/adriannproglems

func main() {
	secret := rand.Int() % 500

	oldguess := secret
	var guess int

	fmt.Printf("Enter your guess: ")
	fmt.Scanf("%d", &guess)
	tries := 1
	for guess != secret {
		if guess < secret {
			fmt.Println("Too low!")
		} else if guess > secret {
			fmt.Println("Too high!")
		}
		fmt.Printf("Enter your guess: ")
		fmt.Scanf("%d", &guess)

		if guess != oldguess {
			tries++
		}
		oldguess = guess
	}
	fmt.Printf("That's correct, the number was %v\n", secret)
	fmt.Printf("You used %v tries", tries)
}

示例#9
文件: 1B.go 项目: giter/codeforces-ans

func main() {

	var n int
	fmt.Scanf("%d\n", &n)
	re := regexp.MustCompile("(R\\d+C\\d+)|(([A-Z]+)(\\d+))")

	for i := 0; i < n; i++ {

		var k string
		fmt.Scanf("%s\n", &k)

		ss := re.FindStringSubmatch(k)

		if len(ss[1]) > 0 {
			var a, b int
			fmt.Sscanf(ss[1], "R%dC%d", &a, &b)
			fmt.Printf("%s%d\n", itos(b), a)
		}

		if len(ss[2]) > 0 {
			a := ss[3]
			var b int
			fmt.Sscanf(ss[4], "%d", &b)
			fmt.Printf("R%dC%d\n", b, stoi(a))
		}
	}

}

示例#10
文件: main.go 项目: scottgw/concurrent-languages

func main() {
	var nrows, ncols, percent int

	flag.Parse()

	fmt.Scanf("%d%d", &nrows, &ncols)

	if !*is_bench {
		for i := 0; i < nrows; i++ {
			for j := 0; j < ncols; j++ {
				fmt.Scanf("%d", &matrix[i][j])
			}
		}
	}

	fmt.Scanf("%d", &percent)

	thresh(nrows, ncols, percent)

	if !*is_bench {
		for i := 0; i < nrows; i++ {
			for j := 0; j < ncols; j++ {
				fmt.Printf("%d ", mask[i][j])
			}
			fmt.Printf("\n")
		}
		fmt.Printf("\n")
	}
}

示例#11
文件: commands.go 项目: GeorgeChan/upx

func Login(args []string, opts map[string]interface{}) {
	user := &userInfo{CurDir: "/"}
	if len(args) == 3 {
		user.Bucket = args[0]
		user.Username = args[1]
		user.Password = args[2]
	} else {
		fmt.Printf("ServiceName: ")
		fmt.Scanf("%s\n", &user.Bucket)
		fmt.Printf("Operator: ")
		fmt.Scanf("%s\n", &user.Username)
		fmt.Printf("Password: ")
		b, err := gopass.GetPasswdMasked()
		if err == nil {
			user.Password = string(b)
		}
	}

	if _, err := NewFsDriver(user.Bucket, user.Username,
		user.Password, user.CurDir, 10, nil); err != nil {
		fmt.Fprintf(os.Stderr, "failed to log in. %v\n", err)
		os.Exit(-1)
	}

	// save
	conf.UpdateUserInfo(user)
	conf.Save(confname)
}

示例#12
文件: 469B.go 项目: kronos/Task-solutions

func main() {
	var p, q, l, r int
	fmt.Scanf("%d %d %d %d\n", &p, &q, &l, &r)
	a := make([]int, p)
	b := make([]int, p)
	c := make([]int, q)
	d := make([]int, q)
	for i := 0; i < p; i++ {
		fmt.Scanf("%d %d\n", &a[i], &b[i])
	}

	for i := 0; i < q; i++ {
		fmt.Scanf("%d %d\n", &c[i], &d[i])
	}

	ans := 0
	for t := l; t <= r; t++ {
		f := false
		for i := 0; (i < p) && !(f); i++ {
			for j := 0; (j < q) && !(f); j++ {
				f = (c[j]+t <= b[i]) && (d[j]+t >= a[i])
			}
		}

		if f {
			ans++
		}
	}
	fmt.Println(ans)
}

示例#13
文件: 545B_Equidistant_String.go 项目: DmitryTsybin/Study

func main() {
	var s string
	fmt.Scanf("%s", &s)

	var t string
	fmt.Scanf("%s", &t)

	m := make([]byte, len(s))

	count := 0
	for i := 0; i < len(s); i++ {
		if s[i] != t[i] {
			count += 1
		}
	}

	if count%2 != 0 {
		fmt.Println("impossible")
	} else {
		count = count / 2
		for i := 0; i < len(s); i++ {
			if s[i] != t[i] && count > 0 {
				m[i] = s[i]
				count -= 1
			} else {
				m[i] = t[i]
			}
		}
		fmt.Println(string(m))
	}
}

示例#14
文件: clientMain.go 项目: magicsea/mygoserver

func login(conn net.Conn) {
	// Username
	fmt.Printf("Enter your name: ")
	fmt.Scanf("%s", &writeStr)
	username := string(writeStr)

	// Password
	fmt.Printf("Enter your password: ")
	fmt.Scanf("%s", &writeStr)
	password := string(writeStr)

	in, err := conn.Write([]byte(username + " " + password))
	if err != nil {
		fmt.Printf("Error when send to server: %d\n", in)
		os.Exit(0)
	}

	length, err := conn.Read(readStr)
	if err != nil {
		fmt.Printf("Error when read from server. Error:%s\n", err)
		os.Exit(0)
	}
	if string(readStr[:length]) == "login error" {
		fmt.Println("Login error, try again.")
		login(conn)
	}

}

示例#15
文件: theGridSearch.go 项目: SuhasAnand/Hckrnk

func main() {
	var T int
	fmt.Scanf("%d\n", &T)

	for i := 0; i < T; i++ {
		//Step 1 read the Main matrix
		var m, n int
		fmt.Scanf("%d %d\n", &m, &n)
		mainMat := readMatrix(m, n)

		//Step 2: Read the pattern Matrix
		var pm, pn int
		fmt.Scanf("%d %d\n", &pm, &pn)
		patternMat := readMatrix(pm, pn)

		//Step 3: search for the pattern
		var res bool = false
	loop:
		for i := 0; i < ((m - pm) + 1); i++ {
			for j := 0; j < ((n - pn) + 1); j++ {
				res = verifyMatch(mainMat, i, j, patternMat, pm, pn)
				if res {
					break loop
				}
			}
		}

		//Step 4: Announce the results
		if res {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

示例#16
文件: GemStones.go 项目: knd/hackerrank

func main() {
	var rockSize int
	fmt.Scanf("%d", &rockSize)
	var gemElemSet = make(map[string]bool)
	for i := 0; i < rockSize; i++ {
		var input string
		fmt.Scanf("%s", &input)
		if i == 0 {
			for _, j := range input {
				_, ok := gemElemSet[string(j)]
				if !ok {
					gemElemSet[string(j)] = true
				}
			}
		} else {
			for element, _ := range gemElemSet {
				if !strings.Contains(input, element) {
					delete(gemElemSet, element)
				}
			}
		}
	}
	fmt.Println(len(gemElemSet))

}

示例#17
文件: hellostruct.go 项目: pmcgrath/presentations

func main() {
	var name string // Need vars so we can store scanf results
	var age int

	// Read some input
	fmt.Print("Gimme name :")
	fmt.Scanf("%s", &name) // Using a specific verb and passing a pointer to the name var
	fmt.Print("Gimme age :")
	fmt.Scanf("%d", &age) // Different verb for a number

	p := person{name: name, age: age} // Using composite literal to create with named members, could pass just vals based on sequence, if using named members can do so in any order, could use new(person) which would give us a pointer

	fmt.Printf("p %v\n", p) // Toggle String() method name to show how person is satisying the stringer interface and how this affects output

	fmt.Println()
	passByVal(p)
	fmt.Printf("\tp after passByVal : %v\n", p)

	fmt.Println()
	passByPointer(&p) // Need &p to get a pointer to p as the function expects a *person
	fmt.Printf("\tp after passByPointer : %v\n", p)

	fmt.Println()
	makeHowlerHowl(p) // Pass person to function expecting an interface, since person has a howl method that matches the interface we are good
}

示例#18
文件: solution.go 项目: mohan08p/Competitive_Programming

func main() {
	var T int
	fmt.Scanf("%d", &T)
	var total int
	for T > 0 {
		var N int
		fmt.Scanf("%d", &N)
		total = 1
		flag := 1
		for N > 0 {
			if flag != 0 {
				if total == 1 {
					total += 1
				} else {
					total *= 2
				}
				flag--
			} else {
				total += 1
				flag++
			}
			N--
		}
		fmt.Println(total)
		T--
	}
}

示例#19
文件: TwoStrings.go 项目: ankcrimson/Practice

func main() {

	var t int

	fmt.Scanf("%d", &t)

outer:
	for j := 0; j < t; j++ {

		var str1, str2 string
		fmt.Scanf("%s", &str1)
		fmt.Scanf("%s", &str2)

		var arr [26]bool
		for i := 0; i < 26; i++ {
			arr[i] = false
		}

		for i := 0; i < len(str1); i++ {
			arr[str1[i]-'a'] = true
		}

		for i := 0; i < len(str2); i++ {
			if arr[str2[i]-'a'] {
				fmt.Println("YES")
				//countine=ue outer
				continue outer
			}
		}
		fmt.Println("NO")

	}
}

示例#20
文件: tweetaspike.go 项目: rmondragon/student-workbook

func UpdatePasswordUsingCAS(client *Client) {

	// Get username
	var username string
	fmt.Print("Enter username:")
	fmt.Scanf("%s", &username)

	if len(username) > 0 {
		// Check if username exists
		userKey, _ := NewKey("test", "users", username)
		userRecord, err := client.Get(nil, userKey)
		panicOnError(err)
		if err == nil {
			// Get new password
			var password string
			fmt.Print("Enter new password for %s:", username)
			fmt.Scanf("%s", &password)

			writePolicy := NewWritePolicy(0, 0) // generation = 0, expiration = 0
			// record generation
			writePolicy.Generation = int32(userRecord.Generation)
			writePolicy.GenerationPolicy = EXPECT_GEN_EQUAL
			// password Bin
			passwordBin := NewBin("password", password)
			err = client.PutBins(writePolicy, userKey, passwordBin)
			panicOnError(err)
			fmt.Printf("\nINFO: The password has been set to: %s", password)
		} else {
			fmt.Printf("ERROR: User record not found!")
		}
	} else {
		fmt.Printf("ERROR: User record not found!")
	}
}

示例#21
文件: tweetaspike.go 项目: rmondragon/student-workbook

func queryUsersByTweetCount(client *Client) {

	fmt.Printf("\n********** Query Users By Tweet Count Range **********\n")

	// Get min and max tweet counts
	var min int64
	var max int64
	fmt.Printf("\nEnter Min Tweet Count:")
	fmt.Scanf("%d", &min)
	fmt.Printf("Enter Max Tweet Count:")
	fmt.Scanf("%d", &max)

	fmt.Printf("\nList of users with %d - %d tweets:\n", min, max)

	stmt := NewStatement("test", "users", "username", "tweetcount", "gender")
	stmt.Addfilter(NewRangeFilter("tweetcount", min, max))

	recordset, err := client.Query(nil, stmt)
	panicOnError(err)
L:
	for {
		select {
		case rec, chanOpen := <-recordset.Records:
			if !chanOpen {
				break L
			}
			fmt.Printf("%s has %d tweets\n", rec.Bins["username"], rec.Bins["tweetcount"])
		case err := <-recordset.Errors:
			panicOnError(err)
		}
	}
	recordset.Close()
}

示例#22
文件: 4.go 项目: rhtyd/hacklab

func main() {
	stack := NewStack()

	var t int
	fmt.Scanf("%d", &t)
	var expr string
	for ; t > 0; t-- {
		fmt.Scanf("%s", &expr)
		for _, chr := range expr {
			c := string(chr)
			switch c {
			case "(":
				stack.Push(c)
			case ")":
				for {
					if stack.Len() < 1 {
						break
					}
					if stack.Peek() == "(" {
						stack.Pop()
						break
					}
					fmt.Print(stack.Pop())
				}
			case "+", "-", "*", "/", "^":
				stack.Push(c)
			default: //characters
				fmt.Print(c)
			}
		}
		fmt.Println()
	}
}

示例#23
文件: query.go 项目: zscawd12/dbms

func (d *DBMS) CreateTable() error {
	var table, column string

	fmt.Print("\ntable name : ")
	fmt.Scanf("%s", &table)

	fmt.Print("column name(ex. a,b) : ")
	fmt.Scanf("%s", &column)

	query := []byte("table : " + table + " | column : " + column)

	file, err := os.OpenFile(d.FilePath+"/table.txt", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)
	if err != nil {
		d.Logger.Printf("failed to file open : %v", err)
		return err
	}
	defer file.Close()

	_, err = file.Write(query)
	if err != nil {
		d.Logger.Printf("failed to file wirte : %v", err)
		return err
	}

	return nil
}

示例#24
文件: main.go 项目: neetsdkasu/Paiza-POH-MyAnswers

func main() {

	var n int
	fmt.Scanf("%d", &n)

	var w float64 = 0.0
	var c float64 = 0.0

	for i := 0; i < n; i++ {
		var t int
		var s float64
		fmt.Scanf("%d %f", &t, &s)
		switch t {
		case 1:
			w += s
		case 2:
			c += s
		case 3:
			wc := w + c
			w = (w*wc - s*w) / wc
			c = (c*wc - s*c) / wc
		}

	}

	ans := 100.0 * c / (w + c)
	fmt.Printf("%d\n", int(ans))
}

示例#25
文件: tweetaspike.go 项目: rmondragon/student-workbook

func UpdatePasswordUsingCAS(client *Client) {

	// Get username
	var username string
	fmt.Print("Enter username:")
	fmt.Scanf("%s", &username)

	if len(username) > 0 {
		// Check if username exists
		userKey, _ := NewKey("test", "users", username)
		_, err := client.Get(nil, userKey)
		//userRecord, err := client.Get(nil, userKey)
		panicOnError(err)
		if err == nil {
			// Get new password
			var password string
			fmt.Print("Enter new password for %s:", username)
			fmt.Scanf("%s", &password)

			// TODO: Update User record with new password only if generation is the same
			// Exercise 5
			fmt.Printf("\nINFO: The password has been set to: %s", password)
		} else {
			fmt.Printf("ERROR: User record not found!")
		}
	} else {
		fmt.Printf("ERROR: User record not found!")
	}
}

示例#26
文件: cutTheSticks.go 项目: SuhasAnand/Hckrnk

func main() {
	var arrSiz int
	fmt.Scanf("%d\n", &arrSiz)

	array := make([]int, arrSiz, arrSiz)
	for i := 0; i < arrSiz; i++ {
		fmt.Scanf("%d", &array[i])
	}
	for i := 0; i < arrSiz; i++ {
		var j int = 0
		sort.Ints(array)
		for j = 0; j < len(array); j++ {
			min := array[j]
			if min <= 0 {
				continue
			} else {
				break
			}
		}
		array = array[j:]
		if len(array) <= 1 {
			fmt.Println(len(array))
			break
		}
		fmt.Println(len(array))
		min := array[0]
		for j = 0; j < len(array); j++ {
			array[j] -= min
		}
	}

}

示例#27
文件: setup.go 项目: bentranter/lazyblog

// Setup runs our setup process, creating a new DB,
func Setup() {
	var username []byte
	var password []byte

	for username == nil {
		fmt.Printf("Enter a username:\n")
		fmt.Scanf("%s", &username)
	}
	for password == nil {
		fmt.Printf("Enter a password:\n")
		fmt.Scanf("%s", &password)
	}

	hashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		log.Fatalln("There was an error hashing and salting your password: ", err.Error())
		return
	}

	DefaultStore.Update(func(tx *bolt.Tx) error {
		users := tx.Bucket(_users)
		return users.Put([]byte(username), hashed)
	})
	log.Println("Congrats on setting up your Lazyblog! You're all set, try visiting /admin to begin.")
	return
}

示例#28
文件: poisonous_plants_stack.go 项目: yaru22/problem-solving

func main() {
	var n, sol int
	fmt.Scanf("%d\n", &n)
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &arr[i])
	}

	tdeath := make([]int, n)
	stack := make([]int, 1)
	for i := 1; i < n; i++ {
		l := len(stack)
		if arr[i] > arr[stack[l-1]] {
			tdeath[i] = 1
		}
		for l > 0 && arr[i] <= arr[stack[l-1]] {
			if tdeath[i] < tdeath[stack[l-1]]+1 {
				tdeath[i] = tdeath[stack[l-1]] + 1
			}
			stack = stack[:l-1]
			l--
		}

		if len(stack) == 0 {
			tdeath[i] = 0
		}
		stack = append(stack, i)

		if sol < tdeath[i] {
			sol = tdeath[i]
		}
	}
	fmt.Println(sol)
}

示例#29
文件: largest_permutation.go 项目: tommady/Hackerrank

func main() {
	var N, K int
	fmt.Scanf("%d %d\n", &N, &K)

	arr := make([]int, N)
	for i := 0; i < N; i++ {
		fmt.Scanf("%d", &arr[i])
	}

	for i := 0; i < N-1; i++ {
		if K <= 0 {
			break
		}

		maxValue, maxLoc := arr[i], i
		for j := i + 1; j < N; j++ {
			if arr[j] > maxValue {
				maxValue = arr[j]
				maxLoc = j
			}
		}

		if maxLoc != i {
			K--
			arr[i], arr[maxLoc] = arr[maxLoc], arr[i]
		}
	}

	for i := 0; i < N; i++ {
		fmt.Printf("%d ", arr[i])
	}
}

示例#30
文件: userInput.go 项目: ng4mf/life-of-learning

func main() {

	//get a single integer
	var a int
	fmt.Scanf("%d", &a)
	fmt.Println(a)

	//get a string (no spaces)
	var b string
	fmt.Scanf("%s", &b)
	fmt.Println(b)

	//list of n ints
	var myList []int
	fmt.Print("Enter list: ")
	var input string
	fmt.Scanln(&input)
	fmt.Print(input)

	var s scanner.Scanner
	s.Init(input)
	tok := s.Scan()
	for tok != scanner.EOF {
		// do something with tok
		tok = s.Scan()
		asInt, _ := strconv.Atoi(tok)
		myList = append(myList, asInt)
	}

	fmt.Println(myList)

}

展开阅读全文